WooCommerce Ajax Product Search with Custom Code
Implementing an Ajax-based product search in WooCommerce requires setting up a search form, handling Ajax in PHP, and rendering real-time results. Follow these steps:
Step 1: Design the Custom Search Form
Insert the form into your theme (e.g., searchform.php
) or custom plugin:
<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: Add Ajax JavaScript
Create a JavaScript file (e.g., custom-ajax-search.js
) and include the code:
(function ($) { $(document).ready(function () { var searchInput = $('#product-search'); var searchResults = $('#search-results'); searchInput.on('input', function () { var keyword = $(this).val(); $.ajax({ type: 'POST', url: custom_ajax_search.ajax_url, data: { action: 'custom_ajax_product_search', keyword: keyword, }, beforeSend: function () { searchResults.html('<p>Loading...</p>'); }, success: function (response) { searchResults.html(response); }, }); }); }); })(jQuery);
Step 3: Enqueue JavaScript File
Enqueue the JS in your theme’s functions.php
or plugin:
function custom_enqueue_ajax_search_script() { if (is_search()) { wp_enqueue_script('custom-ajax-search', get_stylesheet_directory_uri() . '/custom-ajax-search.js', array('jquery'), '1.0', true); wp_localize_script('custom-ajax-search', 'custom_ajax_search', array('ajax_url' => admin_url('admin-ajax.php'))); } } add_action('wp_enqueue_scripts', 'custom_enqueue_ajax_search_script');
Step 4: PHP Handler for Ajax
Add this in functions.php
or plugin to process Ajax request:
function custom_ajax_product_search() { check_ajax_referer('custom_ajax_product_search', 'security'); $keyword = isset($_POST['keyword']) ? sanitize_text_field($_POST['keyword']) : ''; $args = array( 'post_type' => 'product', 'post_status' => 'publish', 's' => $keyword, 'posts_per_page' => 5, ); $search_query = new WP_Query($args); if ($search_query->have_posts()) { while ($search_query->have_posts()) { $search_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: Final Testing
After saving changes, test the Ajax search on your site. Ensure WooCommerce templates are compatible and consider adding nonces for security.