我正试图按照本教程在WordPress搜索结果中实现typeahead.js-http://code.tutsplus.com/tutorials/enhancing-the-search-form-with-typeaheadjs--wp-30844.
我想通过更改以下代码来扩展其用于wooccommerce产品搜索的功能
( 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 ),
);
当我搜索产品时,它不会显示图像,但会完美地显示标题。当我用firebug检查元素时,它显示了以下代码:
<img src="false">
我该如何解决这个问题?
最后,我通过添加以下代码找到了解决方案:
$img_url = wp_get_attachment_url( get_post_thumbnail_id($the_post->ID) );