September 6, 2024
Ensure you have access to your WordPress theme’s files or a child theme where you can add custom code.
Add a search form to your theme. You can do this by editing the appropriate template file, usually header.php
, sidebar.php
, or a custom page template.
<form id="live-search-form" action="" method="get">
<input type="text" id="live-search-input" name="s" placeholder="Search...">
<div id="live-search-results"></div>
</form>
Add JavaScript to handle user input and make AJAX requests. You can include this script in your theme’s functions.php
or in a separate JavaScript file.
function enqueue_live_search_script() {
wp_enqueue_script('live-search', get_template_directory_uri() . '/js/live-search.js', array('jquery'), null, true);
wp_localize_script('live-search', 'liveSearchParams', array(
'ajax_url' => admin_url('admin-ajax.php')
));
}
add_action('wp_enqueue_scripts', 'enqueue_live_search_script');
Create a file named live-search.js
in your theme’s js
directory:
jQuery(document).ready(function($) {
$('#live-search-input').on('keyup', function() {
var query = $(this).val();
if (query.length > 2) { // Adjust the number of characters needed to trigger the search
$.ajax({
url: liveSearchParams.ajax_url,
type: 'GET',
data: {
action: 'live_search',
s: query
},
success: function(response) {
$('#live-search-results').html(response);
}
});
} else {
$('#live-search-results').empty();
}
});
});
4. Create the AJAX Handler in functions.php
Add an AJAX handler to process the search query and return results.
function live_search_handler() {
if (isset($_GET['s'])) {
$search_query = sanitize_text_field($_GET['s']);
$args = array(
'post_type' => 'post', // Adjust this if you're searching custom post types
's' => $search_query
);
$query = new WP_Query($args);
if ($query->have_posts()) {
echo '<ul>';
while ($query->have_posts()) {
$query->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php
}
echo '</ul>';
} else {
echo 'No results found.';
}
wp_reset_postdata();
}
wp_die(); // Required to terminate immediately and return a proper response
}
add_action('wp_ajax_live_search', 'live_search_handler');
add_action('wp_ajax_nopriv_live_search', 'live_search_handler');
Add some CSS to style the search results as needed. You can include this in your theme’s style.css
.
#live-search-results {
border: 1px solid #ddd;
padding: 10px;
background: #fff;
}
#live-search-results ul {
list-style: none;
margin: 0;
padding: 0;
}
#live-search-results li {
margin-bottom: 10px;
}
#live-search-results a {
text-decoration: none;
color: #333;
}
After implementing the code, test the live search functionality on your WordPress site. Type in the search input field and check if results appear dynamically as you type.
By following these steps, you’ll have a live search feature on your WordPress site that updates search results in real-time based on user input. Adjustments might be needed based on your specific theme and requirements.