Search is one of the most important parts of any WordPress website, but the default search system is very limited.
A smart AJAX search with live suggestions can dramatically improve user experience and engagement.
In this article, you will learn how to build a lightweight live search suggestion system using WordPress hooks and AJAX.
Why Smart Search Matters
Users don’t want to wait for a full page reload just to find a product or article.
Live search suggestions solve this problem instantly.
- Faster content discovery
- Improved user experience
- Higher engagement time
- Better WooCommerce conversions
The WordPress Hooks We Will Use
We will use:
wp_enqueue_scripts
wp_ajax_*
wp_ajax_nopriv_*
These hooks allow us to load scripts and handle AJAX requests for both logged-in and guest users.
Step 1: Add AJAX Script
add_action('wp_enqueue_scripts', 'smart_search_scripts');
function smart_search_scripts() {
wp_enqueue_script('jquery');
wp_add_inline_script('jquery', "
jQuery(document).ready(function($) {
$('#smart-search').on('keyup', function() {
let query = $(this).val();
if (query.length < 2) {
$('#search-results').html('');
return;
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'smart_search',
keyword: query
},
success: function(response) {
$('#search-results').html(response);
}
});
});
});
");
}
Step 2: Handle AJAX Request
add_action('wp_ajax_smart_search', 'smart_search_callback');
add_action('wp_ajax_nopriv_smart_search', 'smart_search_callback');
function smart_search_callback() {
$keyword = sanitize_text_field($_POST['keyword']);
$query = new WP_Query(array(
's' => $keyword,
'posts_per_page' => 5
));
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo '';
}
} else {
echo 'No results found
';
}
wp_die();
}
How It Works
- User types in search field
- AJAX sends request to WordPress
- WordPress returns matching posts
- Results appear instantly without reload
Frontend Example (HTML)
Advanced Improvements
- Search WooCommerce products only
- Add product thumbnails in results
- Highlight matched keywords
- Add debounce for performance
