WordPress Ajax Search Without Plugin [ Easy ] | Code For Developers

WordPress Ajax Search without plugin [ Easy ]

WordPress Ajax Search without plugin. Fully custom code work with woocommerce as well

WordPress Default Search is Not cool. we are going to create WordPress Ajax Search without plugin that will look something like this.

WordPress Ajax Search without plugin

First We need to Create an input Field so users can search. Put it anywhere page template, single.php, archive.php, index.php, page.php, or anywhere you want to show the search field

Search page
<div class="search_bar">
    <form action="/" method="get" autocomplete="off">
        <input type="text" name="s" placeholder="Search Code..." id="keyword" class="input_search" onkeyup="mukto_search_fetch()">
        <button>
            Search
        </button>
    </form>
    <div class="search_result" id="datafetch">
        <ul>
            <li>Please wait..</li>
        </ul>
    </div>
</div>

Main code for WordPress Ajax Search without plugin

Now put the below code to functions.php On the post query you can customize your HTML as you want. This code will interact with HTML to achieve our goal of creating wp Ajax Search without plugin.

functions.php
<?php 
/*
 ==================
 Ajax Search
======================	 
*/
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function mukto_search_fetch(){

    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').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(){

    $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('page','post') ) );
    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() ); ?>"><?php the_title();?></a></li>

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

    die();
}

Ajax Search for Custom post type

This code will be show result from page & post but if you want you can activate if for your wp custom post type as well. Simply you need to change ‘post_type’ => array(‘page’,’post’) to ‘post_type’ => array(‘your_custom_post_type’)

If search not work use this code [Most of the time not need ]

only if custom post type not show in search result
/**
 * This function modifies the main WordPress query to include an array of 
 * post types instead of the default 'post' post type.
 *
 * @param object $query The main WordPress query.
 */
function mukto_post_type_include( $query ) {
    if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
        $query->set( 'post_type', array( 'post', 'page', 'custom_post_type' ) );
    }
}
add_action( 'pre_get_posts', 'mukto_post_type_include' );

Learn more about WordPress Ajax here

WP ajax search result issue [ Fixed ]

Our WordPress Ajax Search without plugin Is working 😍 But there is still an issue. Sometimes it shows all posts when you do 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

Custom.js
$("input#keyword").keyup(function() {
      if ($(this).val().length > 2) {
        $("#datafetch").show();
      } else {
        $("#datafetch").hide();
      }
    });
Style.css
div.search_result {
  display: none;
}

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

To show password-protected posts in search in the search result

Put this code on functions.php

functions.php
add_filter( 'posts_search', 'include_password_posts_in_search' );
function include_password_posts_in_search( $search ) {
    global $wpdb;
    if( !is_user_logged_in() ) {    
        $pattern = " AND ({$wpdb->prefix}posts.post_password = '')";
        $search = str_replace( $pattern, '', $search );
    }
    return $search;
}

Check Out WooCommerce Ajax Search without Plugin Code

WooCommerce Category base Ajax Product Search Without Plugin

Thank you!

Previous Code

Upload file in hosting server via CPanel corn job

File transfer with Cpanel Cron job. Transfer file ...

Next Code

Cookie Popup with jQuery

Browser cookies popup accept, store cookies in bro ...

Leave a Reply

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

59 Comments

  • Frank says:

    I get a console error on this line $(“input#keyword”).keyup(function(), Uncaught TypeError: $ is not a function. Where does this code need to go, or how best to insert it? Thanks

    • Try this on custom.js file code

      (function ($) {
          "use strict";
      
          jQuery(document).ready(function ($) {
              $("input#keyword").keyup(function() {
                  if ($(this).val().length > 2) {
                    $("#datafetch").show();
                  } else {
                    $("#datafetch").hide();
                  }
                });
          });
      
      }(jQuery));
      
      
      		
      				
  • Luis Morales says:

    Hola gracias por el aporte y como seria si quisiera limitar solo listar cierta cantidad
    de publicaciones en la busqueda y que aparesca un boton ver todos los resultados y me envia al listado de la busqueda en la pagina search,php de wordpress Gracias

    • $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('page','post') ) );
      

      Here you can see ‘posts_per_page’ => -1
      If you want 5 item then put 5 here or value as much you want.

      $the_query = new WP_Query( array( 'posts_per_page' => 5, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('page','post') ) );
      
  • Wajahat says:

    Search worked but its not showing any suggestions using AJAX.

  • Ammar says:

    How can we search in custom fields as well?

  • Luiz says:

    Hello Mukto!
    First congratulations on the teachings. The codes are very well designed and working perfectly.

    I’m a beginner in wordpress & php and I’m having difficulties in uniting “products + categories + sku + description” in the search result.

    I even ventured to try searching by the color attribute. Both unsuccessful.

    If you can, please show me the way to solve this riddle.

    Have a great week.
    Hugs.
    Luiz

  • C9 says:

    Hey bud, good code tho just one mistake.
    If i write “something” in search box, and after i will delete the text, it displays all posts.

  • Emilia says:

    If I search for a tag or a category for a post it doesn’t show up in the search result, is this something that could be added? Now it seems like it only search for title and content.

  • psh says:

    Hi, it’s the best but it has conflict with woocommerce filter widget. When use this code all of the ajax woocommerce widgets (gutenberg) get stuck on “is loading” mode!

  • Olga says:

    This post is awesome, nice job!

    I can suggest a small feature. You can call fetch after a user stops writing in order to make fewer calls.

  • sedsajjad says:

    Thank you, that was perfect

  • Md Jakirul Islam says:

    Hi,

    This is really helpful and easy documentation to use any ajax search functionality. I will always follow this.

    Thank you so much for this valuable resource.

    Thank you!
    Jakir

  • Miguel Zaragoza says:

    Hi? I like your codes it work. But can you help me how can make this 1 search and it will seach my 2 website contents. Like if add this function and I search one of my website it will show also the data.

  • Lester says:

    Hi, I love the code. it really works well. but can you add some dropdown filter on taxonomy? i want to filter it using taxonomy…

  • Oliviercreativ says:

    Attention, with woocommerce, stripe and woocommerce payment there is a conflict in the order page, you cannot select the registered credit card.

    Otherwise it works great, thanks!

  • Seb says:

    Hi,
    thanks for your help 🙂
    But I have a question. If I would like to separate this into the main blog page and into sub-pages with categories, how can I make it, that on a sub-page with a category, when I type something into the search engine, will be displayed only posts assigned to that specific category. And on the main blog page, with all posts, it would search by all posts.

  • Albert Garrett says:

    Works well, But how to disable the keyboard ENTER function on the search, this reloads the page.

  • Greg says:

    Fantastic post and this worked a charm! Be great if you could do a vanilla JS version too!

  • Evan says:

    Hi,

    Thank you for sharing this.

    I am getting an error in the console:

    Uncaught (in promise) TypeError: Failed to execute ‘fetch’ on ‘Window’: 1 argument required, but only 0 present. at HTMLInputElement.onkeyup

    And apparently this blocks the results from showing.

    What could be causing this?

  • Tom says:

    This is working great until I need it to search password-protected posts… if you are not logged in, it does not return anything that is password-protected, it will only display them if you are logged in as an admin… Any thoughts as to why this may be or how to fix it?

    Thanks!

    • mukto says:

      Thanks for finding the issue. Put this code in funtions.php Hope it will work!
      I just tested and update the post. Kudos

      add_filter( 'posts_search', 'include_password_posts_in_search' );
      function include_password_posts_in_search( $search ) {
          global $wpdb;
          if( !is_user_logged_in() ) {    
              $pattern = " AND ({$wpdb->prefix}posts.post_password = '')";
              $search = str_replace( $pattern, '', $search );
          }
          return $search;
      }
      
  • Tanvir Hossain Tofan says:

    nics boss.perfact code style

  • ersezar says:

    The code looks great thanks for sharing! I wonder if it would be possible to include Woocommerce product categories?

  • anshul tiwari says:

    Hi,
    Is it possible to search by author name or emailid

  • Gamal Elwazeery says:

    Nice work
    But I think you should use the character limit on keyup before make an ajax call .. so It wouldn’t make a request before you type a 2 characters

  • zarei says:

    Hello. Can the ability to select a category be added to it?

  • lester says:

    can you do it witch select post type in option method

  • vasilis says:

    Amazing tutorial and really fast search results!
    I just have a question. Is it necessary to add nonce functionality for security reasons and how can I add it?

    Thank you!

  • Sayan says:

    Hello I want to search on basis of taxonomies of post type to show the post listing under related to the taxonomies.
    Thanks in advance.

    • mukto says:

      I think you need to work with query check this part of code and try modify.
      I have a plan to expand this tutorial base on the use case I got from the comment. so keep looking. 🤗

  • Marioo says:

    Hi,
    thank you

    Is it possibile to search only in the title and not on post_content?

    Thank you

    • mukto says:

      Try this hope it’s work –

      
      function __search_by_title_only( $search, &$wp_query )
      {
          global $wpdb;
          if(empty($search)) {
              return $search; // skip processing - no search term in query
          }
          $q = $wp_query->query_vars;
          $n = !empty($q['exact']) ? '' : '%';
          $search =
          $searchand = '';
          foreach ((array)$q['search_terms'] as $term) {
              $term = esc_sql($wpdb->esc_like($term));
              $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
              $searchand = ' AND ';
          }
          if (!empty($search)) {
              $search = " AND ({$search}) ";
              if (!is_user_logged_in())
                  $search .= " AND ($wpdb->posts.post_password = '') ";
          }
          return $search;
      }
      add_filter('posts_search', '__search_by_title_only', 500, 2);
      
      
  • Luis Kabes says:

    Hello Mukto, thanks for the tutorial, it’s working. But, how to show the query when user search by SKU products? i’ve try to install relevanssi but it’s still not working.

    Thank you

    • mukto says:

      Try this hope it work.

      function search_by_sku( $search, &$query_vars ) {
          global $wpdb;
          if(isset($query_vars->query['s']) && !empty($query_vars->query['s'])){
              $args = array(
                  'posts_per_page'  => -1,
                  'post_type'       => 'product',
                  'meta_query' => array(
                      array(
                          'key' => '_sku',
                          'value' => $query_vars->query['s'],
                          'compare' => 'LIKE'
                      )
                  )
              );
              $posts = get_posts($args);
              if(empty($posts)) return $search;
              $get_post_ids = array();
              foreach($posts as $post){
                  $get_post_ids[] = $post->ID;
              }
              if(sizeof( $get_post_ids ) > 0 ) {
                      $search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $get_post_ids ) . ")) OR (", $search);
              }
          }
          return $search;
          
      }
          add_filter( 'posts_search', 'search_by_sku', 999, 2 );
      
  • Андрей says:

    Идеальный пример! Спасибо)))

  • DenDionigi says:

    Amazing tutorial.
    Can you also make a plain vanilla js (with “xmlHttpRequest();”) ?

    Thank you

If you find it useful

Buy me a coffee

ACF

Elementor

JavaScript

jQuery

Others

PHP

WooCommerce

WordPress

WP Plugin Dev

Conditional statement to show pagination

Conditional statement to show pagination on WordPr ...

Add Custom element item in wp nav menu

Add Element on last item of wp nav menu ...

WordPress .htaccess code for redirect www to non www url

Remove www from url or redirect ...

Change WordPress URL in Database with phpMyAdmin and SQL query

Replace WordPress old URL to new URL with SQL Quer ...

wp-config development code

WordPress post revisions, debug, load-scripts.php ...

top