In this tutorial, we will learn how to enhance the WordPress search functionality of a WordPress website by implementing an autocomplete feature using AJAX. Autocomplete allows users to receive real-time suggestions as they type in the search input, making the search process more convenient and efficient. We will use jQuery UI’s Autocomplete widget and leverage WordPress AJAX functionality to fetch and display search suggestions dynamically.
Prerequisites – WordPress Search
Before we begin, ensure that you have a basic understanding of HTML, JavaScript, and WordPress development. Additionally, make sure you have a WordPress theme set up and access to modify theme files.
Setting up the HTML Markup for WordPress Search
First, let’s include the search input field in our theme file where we want the autocomplete feature to be displayed. Add the following code wherever you want to place the search input:
<?= get_search_form(); ?>
Creating the JavaScript File
Next, we need to create a JavaScript file to handle the autocomplete functionality for WordPress Search. Create a new file named custom-script.js
and save it in the js
folder of your theme. This file will contain the necessary code to initialize the autocomplete feature. Open custom-script.js
and add the following code:
// custom-script.js
jQuery(document).ready(function($) {
var autocompleteInput = $('.search-field');
var suggestionsList = $('#suggestions');
autocompleteInput.autocomplete({
source: function(request, response) {
$.ajax({
url: myAjax.ajaxurl,
dataType: 'json',
data: {
action: 'search_autocomplete',
term: request.term
},
success: function(data) {
var suggestions = data.data;
response($.map(suggestions, function(suggestion) {
return {
label: suggestion,
value: suggestion
};
}));
}
});
},
minLength: 2,
select: function(event, ui) {
autocompleteInput.val(ui.item.value);
return false;
}
}).autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>")
.append("<div>" + item.label + "</div>")
.appendTo(ul);
};
autocompleteInput.on('blur', function() {
autocompleteInput.autocomplete('close');
});
});
Enqueue the Custom Autocomplete Script – WordPress Search
Now, let’s enqueue the custom-script.js
file we created earlier. Add the following code to your functions.php
file:
// functions.php
function enqueue_custom_autocomplete_script() {
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery-ui-autocomplete' ), '1.0', true );
wp_localize_script( 'custom-script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_custom_autocomplete_script' );
Implementing the AJAX Callback for WordPress Search
To fetch and display the autocomplete suggestions, we need to create an AJAX callback function. Open your functions.php
file again and add the following code:
// functions.php
function search_autocomplete_callback() {
$term = sanitize_text_field( $_GET['term'] );
// Perform your search logic here and retrieve the autocomplete suggestions
// Example: Fetching autocomplete suggestions from a custom post type 'doctors'
$get_doctor_list_post = array(
'post_type' => 'doctors',
'post_status' => 'publish',
'order' => 'ASC',
'orderby' => 'menu_order',
'posts_per_page' => -1,
);
$get_doctor = get_posts($get_doctor_list_post);
$suggestions = array();
foreach ($get_doctor as $doctor) {
$suggestions[] = $doctor->post_title;
}
$response = array(
'data' => $suggestions,
'wrapper' => '<div class="suggestions-wrapper">%s</div>',
);
wp_send_json($response);
}
add_action( 'wp_ajax_search_autocomplete', 'search_autocomplete_callback' );
add_action( 'wp_ajax_nopriv_search_autocomplete', 'search_autocomplete_callback' );
Creating the Search Results Template
Finally, let’s create a template file to display the search results. Create a new file called search-results.php
in your theme’s root folder. Customize the template as per your requirements to display the search results.
Explanation of Autocomplete Implementation: Now that we have gone through the code, let’s understand how the autocomplete feature works:
-
- When the page loads, the JavaScript code in
custom-script.js
is executed. - The
autocompleteInput
variable selects the search input field using its class. - The
autocomplete
function is called on the input field, configuring the Autocomplete widget. - The
source
option specifies the URL to send the AJAX request for retrieving autocomplete suggestions. - The AJAX request is made to the
search_autocomplete_callback
function defined infunctions.php
, passing the search term. - In the callback function, you can perform your custom search logic and retrieve the autocomplete suggestions.
- The suggestions are returned as an array in the JSON response.
- The Autocomplete widget’s
response
function maps the suggestions to the required format and displays them. - When a suggestion is selected, the
select
function sets the selected value in the input field. - The
_renderItem
function customizes the rendering of each suggestion item in the dropdown list. - The
blur
event listener ensures the dropdown is closed when the input field loses focus.
- When the page loads, the JavaScript code in
Conclusion
Congratulations! You have successfully implemented the autocomplete search feature in WordPress using AJAX. Users will now experience real-time suggestions as they type in the search input field, enhancing their search experience on your WordPress website.
Feel free to customize the code further according to your specific requirements and styling preferences. Happy coding!
Explore More: “Solving Rest API CORS Issues in WordPress as a Headless CMS”
Great post. I waas checking constantly this blog and I’m impressed!
Extremely helpful info specially the remaining section 🙂 I care for such info a lot.
I was looking for this certain information for a very lengthy time.
Thank you and best of luck.
Feel free to visit my web site :: https://Supportvavada.Populiser.com/