Customize WooCommerce Product Search

How to Customize WooCommerce Product Search with AJAX

Getting your Trinity Audio player ready...

Step 3: Add AJAX to Your Search Form

Next, we need to integrate AJAX functionality. This will allow our search form to send the query without reloading the page.

First, enqueue the necessary JavaScript and localize the script to allow AJAX functionality in WooCommerce. You can add this to your theme’s functions.php file:

function custom_woocommerce_ajax_search() {
    wp_enqueue_script( 'ajax-search', get_template_directory_uri() . '/js/ajax-search.js', array( 'jquery' ), null, true );

    wp_localize_script( 'ajax-search', 'ajax_search_params', array(
        'ajax_url' => admin_url( 'admin-ajax.php' )
    ));
}
add_action( 'wp_enqueue_scripts', 'custom_woocommerce_ajax_search' );

This will enqueue the ajax-search.js file, which we will create in the next step, and localize our AJAX parameters.

Step 4: Implement AJAX Logic with JavaScript

Now, create a JavaScript file named ajax-search.js in your theme’s js directory. This script will handle the AJAX requests and display the search results dynamically:

jQuery(document).ready(function($) {
    $('#s').on('keyup', function() {
        var searchQuery = $(this).val();

        $.ajax({
            url: ajax_search_params.ajax_url,
            type: 'POST',
            data: {
                'action': 'woocommerce_ajax_search',
                'search': searchQuery
            },
            success: function(data) {
                $('#product-results').html(data);
            }
        });
    });
});

In this script, we’re listening for input changes in the search field (#s). When a user types a query, it sends an AJAX request to WordPress (via admin-ajax.php), which we will handle in the next step.

Similar Posts