Code Ajax Product Search for WooCommerce Easily
Want real-time WooCommerce search? Here’s a complete guide to building a custom Ajax product search using code.
Step 1: Build a Search Form
Start by adding a custom form in your template (like searchform.php
):
<form role="search" method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <input type="text" placeholder="Search for products..." name="s" id="product-search" /> <div id="search-results"></div> </form>
Step 2: JavaScript for Ajax Request
Use this JS (saved as custom-ajax-search.js
) to trigger live search:
(function ($) { $(function () { var input = $('#product-search'); var results = $('#search-results'); input.on('input', function () { var keyword = $(this).val(); $.post(custom_ajax_search.ajax_url, { action: 'custom_ajax_product_search', keyword: keyword, }, function (data) { results.html(data); }); }); }); })(jQuery);
Step 3: Load JS in WordPress
Include this code in functions.php
to enqueue the script:
function custom_enqueue_ajax_search_script() { if (is_search()) { wp_enqueue_script('custom-ajax-search', get_stylesheet_directory_uri() . '/custom-ajax-search.js', ['jquery'], '1.0', true); wp_localize_script('custom-ajax-search', 'custom_ajax_search', ['ajax_url' => admin_url('admin-ajax.php')]); } } add_action('wp_enqueue_scripts', 'custom_enqueue_ajax_search_script');
Step 4: Create PHP Handler
Paste this function in functions.php
to return products:
function custom_ajax_product_search() { check_ajax_referer('custom_ajax_product_search', 'security'); $keyword = sanitize_text_field($_POST['keyword'] ?? ''); $args = [ 'post_type' => 'product', 'post_status' => 'publish', 's' => $keyword, 'posts_per_page' => 5, ]; $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); wc_get_template_part('content', 'product'); } wp_reset_postdata(); } else { echo 'No products found.'; } wp_die(); } add_action('wp_ajax_custom_ajax_product_search', 'custom_ajax_product_search'); add_action('wp_ajax_nopriv_custom_ajax_product_search', 'custom_ajax_product_search');
Step 5: Test It Live
After setup, test the Ajax product search on the frontend. Ensure WooCommerce is configured and always use proper security best practices.