I have created a live search field that fetches the title of the product using AJAX.
It works correctly, however, I would like to fetch the product thumbnail and the ‘Add to the cart’ button.
**Edit: I have added the output for the thumbnail and add to cart button. It works, but it only displays in singular rows. How can I update my output in rows of 4 as below?
Front End Code
<input type="text" name="keyword" id="keyword" onkeyup="fetch()">
<div id="datafetch">Your numbers will show here</div>
<script>
function fetch(){
$.post('<?php echo admin_url('admin-ajax.php'); ?>',{'action':'my_action'},
function(response){
$('#datafetch').append(response);
console.log(result);
});
}
</script>
Code in Functions.php
<?php
}// LOTTERY start the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'product' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();
global $product;
$product = get_product( get_the_ID() ); //set the global product object
$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {?>
<h4><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h4>
<h4><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_post_thumbnail();?></a></h4>
<p><?php echo $product->get_price_html(); ?></p>
<?php woocommerce_template_loop_add_to_cart(); //ouptput the woocommerce loop add to cart button ?>
<?php
}
endwhile;
wp_reset_postdata();
endif;
die();
}
2
Answers
You can use this
get_the_post_thumbnail_url(get_the_ID())
to get thumbnail URL and add image.You can use this
https://yourdomain.com/?add-to-cart=<product_id>
to add product add to cart URL.https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/
Try this approach