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 ...

Next Code

Add an additional custom checkbox in the WooCommerce checkout

Add an additional custom checkbox after the terms ...

Leave a Reply

Your email address will not be published. Required fields are marked *

twenty − six =

7 Comments

  • Al Amin says:

    It’s working awesomely.😄
    কিন্তু আপনার দেয়া script.js এবং “Hide result before ajax action with css” এই ২টা ফাইল কোথায় অ্যাড করবো তা-ই বুঝতেসি না.😥 আমি parent theme ব্যবহার করি, কোনো child theme নেই।
    কাইন্ডলি যদি বঅলে দেন কোডগুলো কোন ফাইলে অ্যাড করবো তাহলে সুবিধা হতো। অথবা এই script.js & “Hide result…”
    এর কোড গুলো কি উপরের শুধু Html & functions.php এর কোডগুলোর সাথে combine করা যেতে পারে.?

    আরেকটা বিষয় ভাইয়া, আপনার এই মেথডটা কি Code Snippet plugin ব্যবহার করে এপ্লাই করা যেতে পারে.?

    এতো সুন্দর একটা টিউটোরিয়াল দেয়ার জন্য অসংখ্যবার Thank you.😄
    এই বিষয়ে ভালো কোনো আরটিক্যল খুজে পাচ্ছিলাম না, অবশেষে নিজেদের কারো থেকে এতো সুন্দর টিউটোরিয়াল পেয়ে খুব ভালো লাগলো।😌

    • You can use the wp_enqueue_scripts method. also, you can edit your current theme CSS and js file.

      But if you are looking for easy copy-paste code. Then here you go. Let me know if it’s not working as I did not check from my end. Hope it will work!

      Put it at the end of the functions.php file
      BTW you can use Code Snippet plugin too.
      Thanks

  • Harry says:

    This is great, thanks! Quick question. If you only wanted to search the product name within a specific category, what would you need to change in the code?

    • mukto says:

      Thanks, Harry. Then I think you don’t need a category filter option. Follow this WordPress Ajax Search without plugin post.
      And on this part of the code do like this

      $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'     => 10,
                      'operator'  => 'IN',
                  )
             )
          ) 
      );

      Did you notice put 10

      array(
          'taxonomy'  => 'product_cat',
          'field'     => 'term_id',
          'terms'     => 10,
          'operator'  => 'IN',
      )

      Put specific category ID as you want.
      Thanks!

    • Harry says:

      Thanks Mukto. This is perfect.

  • ersezar says:

    It’s good to stop needing plugins for things that don’t require a lot of code!

    Thanks for these useful posts!

skype

Need Coding Help?

Connect Skype

ACF

JavaScript

jQuery

Others

PHP

WooCommerce

WordPress

Add an additional custom checkbox in the WooCommerce checkout

Add an additional custom checkbox after the terms ...

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

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

WooCommerce Checkout Conflict with Bootstrap 4.x

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

Get WooCommerce product info

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

Update WooCommerce Delivery cost with condition

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

top