How to Add Ajax Search to WordPress Without Using a Plugin? (2024)

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 jsadd_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 functionadd_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.
How to Add Ajax Search to WordPress Without Using a Plugin? (2024)

FAQs

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

Simply copy the shortcode, find a page or a post where you'd like to include it and paste the shortcode into a shortcode block. That's all you have to do. To add live search as a widget, navigate to Appearance > Widgets. Search for Ajax Search Lite in the widgets and add it to the area where you want to display it.

How to use AJAX in WordPress without plugins? ›

How to Make an AJAX Call in WordPress?
  1. Step 1: Create the JavaScript File. First off, create a JavaScript file (like custom. ...
  2. Step 2: Register the AJAX Action in functions.php. ...
  3. Step 3: Create the Button and Target Element in Your Blog Posts. ...
  4. Step 4: Enqueue the JavaScript File. ...
  5. Step 5: Testing.
Jan 4, 2024

How to add AJAX search in WordPress? ›

Simply copy the shortcode, find a page or a post where you'd like to include it and paste the shortcode into a shortcode block. That's all you have to do. To add live search as a widget, navigate to Appearance > Widgets. Search for Ajax Search Lite in the widgets and add it to the area where you want to display it.

How to add a custom search bar in WordPress without a plugin? ›

2.1 Using the WordPress Widget Panel

All you have to do is navigate to the WordPress widgets. Navigate to Appearance → Widgets from your WordPress dashboard. Look for the widget named Search, as shown below. Then, on the search widget, click the section where you want the search bar to appear.

How to enable AJAX in WordPress? ›

How to Use Ajax by Working With an Example Plugin (3 Steps)
  1. Step 1: Create the Appropriate File Structures. First, you'll need to name your plugin and create the appropriate file structures for it. ...
  2. Step 2: Choose Some Sample Code to Start With. ...
  3. Step 3: Hook Actions into Your Code. ...
  4. Step 4: Test and Debug Your Plugin.
Jan 5, 2024

Can I use AJAX without URL? ›

Without a URL, you would need to use the server's IP address to call an API using Ajax. In other words, you have to have something that will route your Ajax call to the proper server. That is normally done using a URL.

Can I use AJAX with PHP? ›

To send data to the server using AJAX in PHP, you can include the data in the request payload or as URL parameters, depending on the HTTP method (e.g., POST or GET) you choose. On the server side, you can retrieve the data using PHP's $_POST or $_GET superglobal variables.

How to make AJAX search? ›

Steps to create search example using AJAX in Java
  1. Create table in database.
  2. load the org.json.jar file.
  3. Create input form.
  4. Create server side page to search employee using name.

What is AJAX search in WordPress? ›

Description. Ajax Search Lite is a live search plugin for WordPress. This responsive live search engine, which will boost your user experience by providing a user friendly ajax powered search form – a live search bar. You can filter the results with the category and post type filter boxes as well.

How do I create a custom search filter in WordPress? ›

  1. Creating the custom search form. You start by inserting a View block into your page. In the View creation wizard, enable the Search option. Enabling the custom search when creating a new View. ...
  2. Creating the search results. The results of a custom search is basically a list of posts. In Toolset, we call such lists Views.

How do I customize my search in WordPress? ›

From the WordPress dashboard, navigate to Appearance > Editor. Then, click 'Templates' followed by 'Search' on the left-hand side. Now, you can add, remove, or customize blocks to design your search page. You might want to include the 'Post Title', 'Post Content', and 'Post Date' blocks for each search result.

How do I make a custom field searchable in WordPress? ›

This can be done using a plugin such as Advanced Custom Fields or by manually adding the custom field to the wp_postmeta table in your database. Modify the search query: Next, you'll need to modify the search query to include the custom field data. This can be done by using the pre_get_posts action in WordPress.

How do I get the AJAX URL in WordPress? ›

For getting the value of WordPress' AJAX URL you use admin_url('admin-ajax. php') (yes, “admin url” for frontend). When enqueuing a frontend script that will perform AJAX requests in your theme or plugin, you need to pass on WordPress' AJAX URL as variable to that Javascript, by using wp_localize_script() .

How to check if AJAX is enabled? ›

Here are the steps:
  1. Right-click on your browser to trigger (see the respective instructions on how to enable the Developer menu for Chrome browser or Safari browser).
  2. Click on the Network tab.
  3. Verify the presence of ka.src. If ka. src is not present, the page is not AJAX-enabled. Otherwise, the page is AJAX-enabled.
Feb 15, 2024

What is the hook for AJAX in WordPress? ›

This hook allows you to handle your custom AJAX endpoints. The wp_ajax_ hooks follows the format “ wp_ajax_$action “, where $action is the ' action ' field submitted to admin-ajax. php . This hook only fires for logged-in users.

How to submit data using AJAX in WordPress? ›

Submit Form Using AJAX In WordPress
  1. Create Form For Sending Data With AJAX. First of all, let's create a basic form, which will POST data asynchronously to the server. ...
  2. jQuery Part. ...
  3. Setup WordPress Function For Handling AJAX Request. ...
  4. Further Enhancing Security With Nonce.

Can AJAX be used without jQuery? ›

Yes. You can write your own AJAX code in plain Javascript, or use any non-jQuery framework that has AJAX routines already included.

How to fetch data from database in WordPress without plugin? ›

The first option you can try is a query. This command allows you to retrieve data from your database in WordPress easily. You can retrieve all the content in your site's database using MySQL queries. The query will also include a loop that, by default, follows your parent theme code for your stored data will appear.

How to handle AJAX request in WordPress? ›

AJAX requests in WordPress are handled by the admin-ajax. php file located in the wp-admin folder. It is the designated file for both back-end and user-facing AJAX functionalities. To initiate an AJAX request, it is necessary to include an action parameter with the request data using either the GET or POST method.

Top Articles
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 5614

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.