Implementing Custom Code with JavaScript and AJAX
For a fully custom solution, you can use plain JavaScript and WordPress’s built-in AJAX functionality to create an autocomplete search. This method offers the most flexibility and control over the search feature.
Step 1: Create the Search Form
- Add a search form to your theme (e.g., in header.php).
<form id="searchform" action="<?php echo home_url('/'); ?>" method="get">
<input type="text" id="search-input" name="s" placeholder="Search...">
<input type="submit" value="Search">
</form>
Step 2: Add JavaScript for Autocomplete:
- Implement JavaScript to handle input events and make AJAX requests.
document.addEventListener('DOMContentLoaded', function() {
const searchInput = document.getElementById('search-input');
searchInput.addEventListener('keyup', function() {
const query = this.value;
if (query.length > 2) {
fetch(`${ajaxurl}?action=search_suggestions&term=${query}`)
.then(response => response.json())
.then(data => {
// Render suggestions
});
}
});
});
Step 3: Handle AJAX Request in WordPress:
- Add the AJAX handler in your functions.php.
function search_suggestions() {
global $wpdb;
$term = sanitize_text_field($_GET['term']);
$results = $wpdb->get_results($wpdb->prepare("SELECT post_title FROM $wpdb->posts WHERE post_title LIKE %s AND post_status = 'publish'", '%' . $wpdb->esc_like($term) . '%'), ARRAY_A);
$suggestions = [];
foreach ($results as $result) {
$suggestions[] = $result['post_title'];
}
wp_send_json($suggestions);
}
add_action('wp_ajax_search_suggestions', 'search_suggestions');
add_action('wp_ajax_nopriv_search_suggestions', 'search_suggestions');
Output: Users will receive search suggestions in real-time as they type in the search box, providing a custom autocomplete experience.
How to Add Autocomplete Search to WordPress?
Adding an autocomplete search feature to your WordPress website can significantly enhance user experience by providing instant search suggestions as users type. This functionality is particularly useful for websites with a large amount of content, helping users find what they’re looking for more efficiently. In this article, we will explore various approaches to implementing autocomplete search in WordPress, detailing each method step-by-step.
These are the following approaches:
Table of Content
- Using a WordPress Plugin
- Implementing Custom Code with jQuery UI
- Using an External Service (e.g. Algolia)
- Implementing Custom Code with JavaScript and AJAX