December 28, 2024
2 min read
Woocommerce Ajax Search without plugin June 17, 2022

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="mukto_fetch()">
        <select name="cat" id="cat" onchange="mukto_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 comes 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 mukto_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

Leave a Reply

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

16 Comments

  • Avatar of Anastasiades Anastasiades says:

    I just add the main function code to the function.php of the child theme and then our search from widgets is working with ajax? Just like that?

  • Avatar of Mikołaj Mikołaj says:

    About my last comment (you can edit it)
    When I changed name of function to e.g fetch1(), filters started to work, so seems like it’s naming issue.

  • Avatar of Mikołaj Mikołaj says:

    Hej Mahidul!
    This code save my life… almost 😛

    I experienced something strange. Woocommerce default filters (price and other) don’t work with this code. Seems like function fetch() is blocking(?) something and price filter cannot load (there is an animation on loading, but it never loads). When I remove function fetch() everything is working. Do you know what may be the problem?

  • Avatar of Saif Saif says:

    How can I make pagination with this filter?? Suppose, I want to show 2 post for each page. How can I do that?

  • Avatar of Pearson Pearson says:

    Hi, It’s wired for my site that the code can’t work on the mobile. But it operated well on the desktop. I searched a lot but couldn’t fine the solution. Can you help me figure on this?

  • Avatar of Al Amin 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

  • Avatar of Harry 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?

    • Avatar of mukto 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!

    • Avatar of Harry Harry says:

      Thanks Mukto. This is perfect.

  • Avatar of ersezar ersezar says:

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

    Thanks for these useful posts!

Remove WooCommerce checkout fields

Remove WooCommerce Checkout field with simple filter hook

Get WooCommerce product info

Show product info in the place as you wish to. It help you to make your custom woocommerce product page layout.

Sticky Menu Show when scrolling up

Header bar only show when scrolling up with simple jQuery and CSS trick.

Cookie Popup with jQuery

Browser cookies popup accept, store cookies in browser with jQuery

Web Development Project in mind?

if you looking for a web developer for paid contribution to your project I am available for work.

Mukto
Mukto

Click the button below to chat with me.