On e-commerce sites, live Ajax search helps users to quickly find the product they would like to buy on your site, This will improve the site’s conversion rate and income.
WordPress does not have live Ajax search by default, in this tutorial we are going to create WordPress Ajax Search without plugin like picture below.

Live Ajax Search In woocommerce products

Add Live Ajax Search In WordPress

Before we start, remember If you are using shared web host, remember that Ajax search may increase web server load Because a new request is sent to the server every time a new character is typed in the search field.

In this tutorial, we will create a customizable Shortcode that will create a Ajax search bar for searching in articles, pages, products and custom post type.

Step 1.Copy Ajax search code snippet to functions.php

In the WordPress dashboard, go to Appearance ➡ Theme File Editor and copy the following code into the theme’s functions.php file and update it.

You must create a child theme before making any changes to functions.php file. Otherwise, the applied changes will be lost after each update.
Create child theme in WordPress step by step [without plugin]

As an alternative method, you can use the Code Snippets plugin to insert your codes into WordPress.

/*
*Ajax search by redpishi.com
*https://redpishi.com/wordpress-tutorials/live-ajax-search-in-wordpress/
*/
add_shortcode( 'asearch', 'asearch_func' );
function asearch_func( $atts ) {
    $atts = shortcode_atts( array(
        'source' => 'page,post,product',
        'image' => 'true'
    ), $atts, 'asearch' );
static $asearch_first_call = 1;
$source = $atts["source"];
$image = $atts["image"];
$sForam = '<div class="search_bar">
    <form class="asearch" id="asearch'.$asearch_first_call.'" action="/" method="get" autocomplete="off">
        <input type="text" name="s" placeholder="Search ..." id="keyword" class="input_search" onkeyup="searchFetch(this)"><button id="mybtn">🔍</button>
    </form><div class="search_result" id="datafetch" style="display: none;">
        <ul>
            <li>Please wait..</li>
        </ul>
    </div></div>';
$java = '<script>
function searchFetch(e) {
var datafetch = e.parentElement.nextSibling
if (e.value.trim().length > 0) { datafetch.style.display = "block"; } else { datafetch.style.display = "none"; }
const searchForm = e.parentElement;	
e.nextSibling.value = "Please wait..."
var formdata'.$asearch_first_call.' = new FormData(searchForm);
formdata'.$asearch_first_call.'.append("source", "'.$source.'") 
formdata'.$asearch_first_call.'.append("image", "'.$image.'") 
formdata'.$asearch_first_call.'.append("action", "asearch") 
AjaxAsearch(formdata'.$asearch_first_call.',e) 
}
async function AjaxAsearch(formdata,e) {
  const url = "'.admin_url("admin-ajax.php").'?action=asearch";
  const response = await fetch(url, {
      method: "POST",
      body: formdata,
  });
  const data = await response.text();
if (data){	e.parentElement.nextSibling.innerHTML = data}else  {
e.parentElement.nextSibling.innerHTML = `<ul><a href="#"><li>Sorry, nothing found</li></a></ul>`
}}	
document.addEventListener("click", function(e) { if (document.activeElement.classList.contains("input_search") == false ) { [...document.querySelectorAll("div.search_result")].forEach(e => e.style.display = "none") } else {if  (e.target.value.trim().length > 0) { e.target.parentElement.nextSibling.style.display = "block"}} })
</script>';
$css = '<style>form.asearch {display: flex;flex-wrap: nowrap;border: 1px solid #d6d6d6;border-radius: 5px;padding: 3px 5px;}
form.asearch button#mybtn {padding: 5px;cursor: pointer;background: none;}
form.asearch input#keyword {border: none;}
div#datafetch {
    background: white;
    z-index: 10;
    position: absolute;
    max-height: 425px;
    overflow: auto;
    box-shadow: 0px 15px 15px #00000036;
    right: 0;
    left: 0;
    top: 50px;
}
div.search_bar {
    width: 600px!important;
    max-width: 90%!important;
    position: relative;
}

div.search_result ul a li {
    margin: 0px;
    padding: 5px 0px;
    padding-inline-start: 18px;
    color: #3f3f3f;
    font-weight: bold;
}
div.search_result li {
    margin-inline-start: 20px;
}
div.search_result ul {
    padding: 13px 0px 0px 0px;
    list-style: none;
    margin: auto;
}

div.search_result ul a {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
}
div.search_result ul a:hover {
    background-color: #f3f3f3;
}
.asearch input#keyword {
    width: 100%;
}
</style>';
if ( $asearch_first_call == 1 ){	
	 $asearch_first_call++;
	 return "{$sForam}{$java}{$css}"; } elseif  ( $asearch_first_call > 1 ) {
		$asearch_first_call++;
		return "{$sForam}"; }}

add_action('wp_ajax_asearch' , 'asearch');
add_action('wp_ajax_nopriv_asearch','asearch');
function asearch(){
    $the_query = new WP_Query( array( 'posts_per_page' => 10, 's' => esc_attr( $_POST['s'] ), 'post_type' =>  explode(",", esc_attr( $_POST['source'] )))  );
    if( $the_query->have_posts() ) :
        echo '<ul>';
        while( $the_query->have_posts() ): $the_query->the_post(); ?>
            <a href="<?php echo esc_url( post_permalink() ); ?>"><li><?php the_title();?></li>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'single-post-thumbnail' );?>                               
<?php if ( $image[0] && trim(esc_attr( $_POST['image'] )) == "true" ) {  ?>  <img src="<?php the_post_thumbnail_url('thumbnail'); ?>" style="height: 60px;padding: 0px 5px;"> <?php }  ?> </a>
        <?php endwhile;
       echo '</ul>';
        wp_reset_postdata();  
    endif;
    die();
}

In the above code, a short code named “asearch” is defined. In the next step, we will explain how to use it.

Step 2.Use “asearch” shortcode

After placing the code from the previous step in “functions.php”, the only thing you need to do is to place the “asearch” shortcode on pages or widgets.

[asearch  image="false" source="product, post, page"]

Image attribute:
If you want thumbnail images of products or feature images of posts to be shown in the results, set the image attribute to true otherwise set it to false. By default, the image attribute is set to true, and if you do not set it, thumbnail images will be displayed.

Wordpress live Ajax search with and without thumbnail

Source attribute:
This attribute determines in which part of the site the search is performed. By default, this attribute searches posts, pages, and products.
Separate the argument you want to search with commas. If you want to search in custom post type, enter its name here.

[asearch] // will search in pages and posts and products
[asearch source="product"] // will search in products
[asearch source="post, page"] // will search in pages and posts
[asearch source="your custom post type name"]  // will search in custom post type

If this article is difficult for you to read in text, you can watch the video version below.

How can I style the live search results to match the design of my WordPress theme?

To style the live search results to match the design of your WordPress theme, you can edit the CSS rules provided in the article’s code snippet. You can modify the styles for the search container, search results, and individual elements like the title, excerpt, and featured image. Make sure to use consistent colors, fonts, and spacing to maintain a cohesive visual appearance with the rest of your website.

Can I display additional information in the live search results, such as post categories or tags?

Yes, you can display additional information in the live search results by modifying the code snippet provided in the article. In the PHP code that generates the search results, you can access post metadata like categories, tags, or custom fields using WordPress functions such as get_the_category(), get_the_tags(), and get_post_meta(). Then, you can include the desired information within the HTML structure of each search result item.

How can I limit the number of search results displayed by the live search?

To limit the number of search results displayed by the live search, you can modify the WordPress query that fetches the search results in the PHP code provided in the article. You can use the ‘posts_per_page’ parameter in the WP_Query arguments to specify the maximum number of results to display. For example, to limit the search results to 5, you can add ‘posts_per_page’ => 5 to the $args array.

Share this post
Maya
Maya

Hi, my name is Maya and I’m a WordPress plugin developer. I created this website to share some of the helpful codes that I’ve used in my own projects.
If you’re looking for a custom plugin for your website, you can contact me by clicking on Hire a developer in the menu. I’d love to hear from you.

Articles: 54

15 Comments

    • In the provided code, both the wp_ajax and wp_ajax_nopriv actions are used, which means the code should work for both logged-in users and guests. However, it seems that the AJAX functionality is not working when you\’re logged out. This issue could be related to a security plugin interfering with the execution of the code.
      Temporarily disable any security plugins you have installed on your WordPress site. These plugins might be blocking AJAX requests from non-authenticated users.

  1. Thanks for answering.

    And if I have more than 10 categories, How to select the category in the short code?

    For example it could be something like this:

    [asearch source=\”post\” category_id=\”7\”]

    So in that way where I insert the shortcode and select post, could select category post besides.

    In your code, how to make it work like that??

    RAFael

  2. Hi…Thanks for the video. Very ussefull…………

    But How can I limit the search to one category post?

    Apreciate your answer…

    RAfael

    • You can add a \”cat\” parameter to WP_Query.
      Find this line of code:

      $the_query = new WP_Query( array( \’posts_per_page\’ => 10, \’s\’ => esc_attr( $_POST[\’s\’] ), \’post_type\’ => explode(\”,\”, esc_attr( $_POST[\’source\’] ))) );

      And replace it with the following line:

      $the_query = new WP_Query( array(
      \’posts_per_page\’ => 10,
      \’s\’ => esc_attr( $_POST[\’s\’] ),
      \’post_type\’ => explode(\”,\”, esc_attr( $_POST[\’source\’] )),
      \’cat\’ => 0000000,

      ));

      And in the code above, replace 0000000 with your desired category ID.

  3. Hi there, thanks for this tutorial. I implemented and it works fine. I\’m just curious how can I add the product\’s SKU and Price to be shown for each product as well? At the moment it just shows the image and title.

    Thanks

  4. How add view more or view all button when more post available. Please tell me . Or comment solution plz….

  5. I\’m not very good at coding especially when it comes to javascript stuff. I wish I could hire you to do this for me but I\’m really not in a position to do that. I thought I could get some help since you already did most of the work from your code above, but I guess not. Thanks anyway, I really appreciate the help.

  6. Thanks a lot for the code, it really helped me out a lot. Could you help me with a little customization? My site is based on custom post types, movies, and actors.
    I want to add two checkboxes under the search input for movies and actors, so before you do a search you select either movies or actors, then the ajax search result will be based on the checkbox that you selected, please how do I go about that? I will be forever grateful if you can help me with that. Thank you.

          • Got it! If you’re familiar with HTML and JavaScript, adding two checkboxes to the search form and specifying the $source variable through JavaScript is pretty easy. You can then add it to “formdata” based on whether the checkboxes are checked or not. If coding isn’t your thing, no worries! You can open a project for me to help you out. Just a heads up though, I’m unable to do these requests for free. Sorry about that!

Leave a Reply

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