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.
When I have attempted to include <?php the_post_thumbnail();?>
it has not displayed within my code. How can I adapt my code to include the thumbnail and associated add-to-cart button?
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
// LOTTERY start add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?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();
$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>
<?php
}
endwhile;
wp_reset_postdata();
endif;
die();
}
CodePudding user response:
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/
CodePudding user response:
Try this approach
//Ajax
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();
$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {
//get image and add-to-cart buttom here
$query->the_post();
global $product;
wc_get_template_part('content', 'product');
//End get image and add-to-cart buttom here
}
endwhile;
wp_reset_postdata();
endif;
die();
}