【发布时间】:2015-03-28 03:19:24
【问题描述】:
我正在尝试通过关注this tutorial - http://code.tutsplus.com/tutorials/enhancing-the-search-form-with-typeaheadjs--wp-30844 在 WordPress 搜索结果中实现 typeahead.js。
我想通过更改以下代码来扩展其用于 woocommerce 产品搜索的功能
( function($) {
$( '.woocommerce-product-search input[name="s"]' )
.typeahead( {
name: 'search',
remote: wp_typeahead.ajaxurl + '?action=ajax_search&fn=get_ajax_search&terms=%QUERY',
template: [
'<p><a href="{{url}}"><img src="{{img_url}}" />{{value}}</a></p>',
].join(''),
engine: Hogan
} )
.keypress( function(e) {
if ( 13 == e.which ) {
$(this).parents( 'form' ).submit();
return false;
}
}
);
} )(jQuery);
这里我添加以下代码
<img src="{{img_url}}" />
在类文件中,我更改了以下函数中的一些代码
public function shapla_woo_ajax_search() {
if ( isset( $_REQUEST['fn'] ) && 'get_ajax_search' == $_REQUEST['fn'] ) {
$search_query = new WP_Query( array(
's' => $_REQUEST['terms'],
'post_type' => 'product',
'posts_per_page' => 10,
'no_found_rows' => true,
) );
$results = array( );
if ( $search_query->get_posts() ) {
foreach ( $search_query->get_posts() as $the_post ) {
$title = get_the_title( $the_post->ID );
$image_url = wp_get_attachment_thumb_url( $the_post->ID );
$results[] = array(
'value' => $title,
'img_url' => $image_url,
'url' => get_permalink( $the_post->ID ),
'tokens' => explode( ' ', $title ),
);
}
} else {
$results[] = __( 'Sorry. No results match your search.', 'wp-typeahead' );
}
wp_reset_postdata();
echo json_encode( $results );
}
die();
}
我在这里修改了以下代码:
$image_url = wp_get_attachment_thumb_url( $the_post->ID );
$results[] = array(
'value' => $title,
'img_url' => $image_url,
'url' => get_permalink( $the_post->ID ),
'tokens' => explode( ' ', $title ),
);
当我搜索产品时,它不显示图像但完美地显示标题。当我通过萤火虫检查元素时,它显示以下代码:
<img src="false">
我该如何解决这个问题?
【问题讨论】:
标签: php ajax wordpress woocommerce typeahead.js