Getting your Trinity Audio player ready...
|
Step 5: Handle the AJAX Request in WordPress
Now, let’s create the backend logic to process the AJAX request and return the search results. Add this function to your theme’s functions.php
file:
function woocommerce_ajax_search() {
$search_query = sanitize_text_field($_POST['search']);
$args = array(
'post_type' => 'product',
'posts_per_page' => 10,
's' => $search_query,
);
$products = new WP_Query( $args );
if( $products->have_posts() ) {
while( $products->have_posts() ) : $products->the_post(); ?>
<div class="product-item">
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</div>
<?php endwhile;
} else {
echo '<p>No products found.</p>';
}
wp_die();
}
add_action( 'wp_ajax_woocommerce_ajax_search', 'woocommerce_ajax_search' );
add_action( 'wp_ajax_nopriv_woocommerce_ajax_search', 'woocommerce_ajax_search' );
This function queries WooCommerce products based on the search term provided by the AJAX request and returns matching products. If no products are found, it will display a “No products found” message.