Image thumbnail suggestion in ajax search result in wordpress by typeahead.js

I am trying to implement typeahead.js in WordPress search result by following this tutorial – http://code.tutsplus.com/tutorials/enhancing-the-search-form-with-typeaheadjs–wp-30844.

I want to extend its functionality for woocommerce product search by changing the following code

Read More
( 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);

here I add the folloing code

<img src="{{img_url}}" />

and inside class file I change some code in the following function

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();
}

here I made change the following code:

            $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 ),
            );

When I search for product, it does not show image but show title perfectly. And when I inspect the element by firebug it is showing the following code:

<img src="false">

How can I solve the problem?

Related posts

Leave a Reply

1 comment