How to Add Ajax Search to WordPress Without Using a Plugin?

Hello guys! Today we are going to create a WordPress Ajax search without a plugin. I’ll also recommend the best free and paid WordPress Ajax search plugins. 

First, we need to create an HTML search box [input field] so users can search. Put it anywhere on the page templateindex.php, archive.php, page.php, or anywhere you want to show the search box.

Add the below code where you want to display an Ajax search box on the page.

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

Add the below code inside the function.php file, which is located at “wp-content/your-theme/function.php“.

<?php 
/*
 ==================
 Simple Ajax Search
======================	 
*/
// add the ajax fetch js
add_action( 'wp_footer', 'fetch_ajax' );
function fetch_ajax() {
?>
<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() },
        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','news') ) );
    if( $the_query->have_posts() ) :?>
      <ul>
      <?php 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; ?>
     </ul>
       <?php wp_reset_postdata();  
    endif;

    die();
}

How to add Ajax to the WordPress default search form

To add an Ajax search feature to the WordPress default search form without using a plugin, you can follow these steps:

  • Create a search form in your WordPress theme’s file. You can use the get_search_form() function to generate the default WordPress search form, or you can create a custom form with an input field.
  • <?php get_search_form();?>
  • Add / enqueue the jQuery library in your theme’s functions.php file, using the wp_enqueue_script function. This will allow you to use jQuery to make an Ajax request to the server.
  • add a custom JavaScript file to your theme to bind a submit event handler to the search form. This event handler will be executed when the user submits the search form.
  • Inside the event handler, use $.ajax() function to make an Ajax request to the server. Set the type option to “POST” and the url option to the URL of the search results page.
  • In the data option of the $.ajax() function, include the search query and any other data that you want to send to the server.
  • In the success callback function of the $.ajax() function, insert the search response data into the page. You can easily use the jQuery html() function to update the content of an element on the page with the search results.
  • In the end, prevent the default form submission behaviour by returning false at the end of the event handler function. This will prevent the page from being reloaded when the form is submitted.
jQuery(document).ready(function($){
  $('#searchform').submit(function(event){
    event.preventDefault();
    var searchQuery = $('#search').val();
    $.ajax({
      type: 'POST',
      url: '/search-results/',
      data: {
        s: searchQuery
      },
      success: function(results){
        $('#search-results').html(results);
      }
    });
    return false;
  });
});

How to add simple search form in WordPress without plugin?

  • Open the theme file where you want to display the search form. This is mostly in the header.php or sidebar.php file.
  • Add the below code to the file where you want to display the search form:
<form role="search" method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">
  <label for="search-field">Search</label>
  <input type="search" id="search-field" name="s" value="<?php echo get_search_query(); ?>">
  <input type="submit" value="Search">
</form>
  • Save the file and refresh the page to see the custom search form.

WordPress jQuery Is Not Defined Error

WordPress has a common issue with the jQuery Is Not Defined Error.

The following are some possible reasons why your WordPress website can display the error “Uncaught ReferenceError: jQuery is not defined“:

  • Conflicting plugins
  • Corrupted jQuery file
  • Blocked CDN-hosted jQuery
  • JavaScript runs incorrectly..

Methods to Resolve the “jQuery is Not Defined” Error in WordPress

Method 1:  Add a Snippet to the wp-config.php File

Add the below code inside the wp-config.php file, which is located at “wp-content/your-theme/wp-config.php“.

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
define('CONCATENATE_SCRIPTS', false);

Method 2: Add the jQuery Library Manually

Add the below code inside the header.php file, which is located at “wp-content/your-theme/header.php“.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Best ajax search plugin for WordPress

There are many good Ajax search plugins available for WordPress. I have added some WordPress plugins for the ajax search form. 

  • Ajax Search Lite: This is a free plugin that allows you to add a live search feature to your WordPress site. It includes a number of customization options and also supports custom post types and taxonomies.
  • Relevanssi – A Better Search: This is a popular free plugin that add a powerful search feature to your site. It includes options for highlighting search terms in the results and for boosting the relevance of certain posts or pages.
  • SearchWP: This is a premium plugin that includes a powerful search engine that can be customized to fit the specific needs of your site. It supports custom fields and taxonomies and includes options for boosting the relevance of certain content.

3 thoughts on “How to Add Ajax Search to WordPress Without Using a Plugin?”

Leave a Comment