WooCommerce Ajax Product Search and Category Filter Without Plugin

WooCommerce Ajax Product Search with Category Filter. Simple code, without any plugin.

Today I will share WooCommerce Ajax Product Search and Category Filter Without Plugin. This code snippet is inspired by my past WordPress Ajax Search without plugin [ Easy ] Tutorial. I got a lot of requests on my email and social media for this code. So let’s make it together.

Our end result will look like this.

Woocommerce Ajax Search without plugin June 17, 2022
WooCommerce Ajax Product Search with Category filter

As in the previous tutorial, we need to make our search bar with HTML. We can put it anywhere as we want to show our search bar. It can be header.php, archive.php, sidebar, or any page template.

From HTML Code
<div class="search_bar">
    <form action="/" method="get" autocomplete="off" id="product_search">
        <input type="text" name="s" placeholder="Search Product..." id="keyword" class="input_search" onkeyup="fetch()">
        <select name="cat" id="cat" onchange="fetch()">
            <option value="">All Categories</option>
            <?php

                // Product category Loop

                $terms = get_terms( array(
                        'taxonomy'   => 'product_cat', 
                        'hide_empty' => true, 
                ));

                // Loop through all category with a foreach loop
                foreach( $terms as $term ) {
                    echo '<option value="'. $term->term_id.'"> '. $term->name .' </option>';
                }
                ?>
        </select>
    </form>
    <div class="search_result" id="datafetch">
        <ul>
            <li>Please wait..</li>
        </ul>
    </div>
</div>

Main code for WooComerce Ajax Product Search

The main ajax functionality is come from this code. put it in functions.php of your custom theme or child theme.

functions.php
 <?php 
/*
 ==================
 * WooCommerce Ajax Product Search Code
 * Live search product Search with Category filter
======================	 
*/
// ajax fetch function
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(), pcat: jQuery('#cat').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });

}
</script>

<?php
}

// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
    if ($_POST['pcat']) {
        $product_cat_id = array(esc_attr( $_POST['pcat'] ));
    }else {
        $terms = get_terms( 'product_cat' ); 
        $product_cat_id = wp_list_pluck( $terms, 'term_id' );
    }
    $the_query = new WP_Query( 
        array( 
            'posts_per_page' => -1, 
            's' => esc_attr( $_POST['keyword'] ), 
            'post_type' => array('product'),
            
            'tax_query' => array(
                array(
                    'taxonomy'  => 'product_cat',
                    'field'     => 'term_id',
                    'terms'     => $product_cat_id,
                    'operator'  => 'IN',
                )
           )
        ) 
    );
    if( $the_query->have_posts() ) :
        echo '<ul>';
        while( $the_query->have_posts() ): $the_query->the_post(); ?>

            <li><a href="<?php echo esc_url( post_permalink() ); ?>"><span><?php the_post_thumbnail('thumbnail')?></span><?php the_title();?></a></li>

        <?php endwhile;
       echo '</ul>';
        wp_reset_postdata();  
    endif;

    die();
}

WooCommerce ajax search result issue [ Fixed ]

Our WooCommerce Ajax Product Search without plugin Now it working 😍 But there is still an issue. Sometimes it shows all posts when you did not write anything on search. To fix this let’s write some jQuery so search results only show when you have more than 2 characters on the search filed

Script.js
$("input#keyword").keyup(function() {
      if ($(this).val().length > 2) {
        $("#datafetch").show();
      } else {
        $("#datafetch").hide();
      }
    });
Hide result before ajax action with css
div.search_result {
    display: none;
}

Put this code on any js file you linked with your theme or child theme. That’s all.

Finally, we are done! if you are interested in the CSS style I use for this screenshot here is the code

Style.css for WooCommerce Ajax Search bar
/*=============
CSS Style for WooCommerce ajax search without plugin base on category filter
==============*/
div.search_result {
    display: none;
}

.search_bar {
    padding: 350px 0;
    margin: 0 auto;
    background: #192132;
}

form {
    display: flex;
    justify-content: space-between;
    max-width: 600px;
    margin: auto;
}

input,
select {
    width: 100%;
    padding: 5px 10px;
    border: 1px solid;
    margin-right: 5px;
}
div#datafetch {
    max-width: 600px;
    margin: auto;
}

div#datafetch ul {
    list-style: none;
    padding: 0;
    background: #1a2132;
}

div#datafetch li img {
    max-width: 50px;
    height: AUTO;
}

div#datafetch li {
    padding: 5px;
    background: #151a29;
    margin-bottom: 5px;
}

div#datafetch ul a span {
    display: inline-block;
    margin-right: 10px;
}

div#datafetch a {
    color: #fff;
}

If You looking for WordPress ajax Search Without Plugin check

WordPress Ajax Search without plugin [ Easy ]

Thank you

Previous Code

Replace add to cart button with the product page link & Change add to cart text

`Replace add to cart button with product single li ...

2 Comments

Leave a Reply

Your email address will not be published.

1 × two =

WooCommerce Checkout Conflict with Bootstrap 4.x

WooCommerce Checkout Conflict with Bootstrap 4.x. ...

WooCommerce Discount based on Cart Item

A discount on the total order with condition based ...

Replace add to cart button with the product page link & Change add to cart text

`Replace add to cart button with product single li ...

Update WooCommerce Delivery cost with condition

Change Delivery price base on what item in cart ...

Get WooCommerce product info

Show product info in the place as you wish to. It ...

ACF

JavaScript

jQuery

Others

PHP

WooCommerce

WordPress

skype

Need Coding Help?

Connect Skype
top