jQuery UI provides the Autocomplete widget that we can easily add to our WordPress default search form. This kind of widget requires a JSON output returned by WordPress after a successful AJAX request. Let's see how to implement this feature.
First of all, we need to register our scripts in the functions.php
file:
function add_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'jquery-ui-autocomplete' );
wp_register_style( 'jquery-ui-styles','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css' );
wp_enqueue_style( 'jquery-ui-styles' );
wp_register_script( 'my-autocomplete', get_template_directory_uri() . '/js/my-autocomplete.js', array( 'jquery', 'jquery-ui-autocomplete' ), '1.0', false );
wp_localize_script( 'my-autocomplete', 'MyAutocomplete', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'my-autocomplete' );
}
add_action( 'wp_enqueue_scripts', 'add_scripts' );
wp_localize_script()
creates the global JavaScript MyAutocomplete
object whose url
property contains the absolute URL to the main AJAX script
used by WordPress ( /wp-admin/admin-ajax.php
). Now we can create our AJAX action in WordPress:
function my_search() {
$term = strtolower( $_GET['term'] );
$suggestions = array();
$loop = new WP_Query( 's=' . $term );
while( $loop->have_posts() ) {
$loop->the_post();
$suggestion = array();
$suggestion['label'] = get_the_title();
$suggestion['link'] = get_permalink();
$suggestions[] = $suggestion;
}
wp_reset_query();
$response = json_encode( $suggestions );
echo $response;
exit();
}
add_action( 'wp_ajax_my_search', 'my_search' );
add_action( 'wp_ajax_nopriv_my_search', 'my_search' );
We've just created a simple search Loop by using the term
parameter passed with the AJAX request. It's time to define our JavaScript code in the
my-autocomplete.js
file:
(function( $ ) {
$(function() {
var url = MyAutocomplete.url + "?action=my_search";
$( "#s" ).autocomplete({
source: url,
delay: 500,
minLength: 3
});
});
})( jQuery );
Since the WordPress AJAX action has been defined as my_search
, we need to pass it to the AJAX script in our URL. The global object created earlier is here used to retrieve the absolute
URL to the main AJAX handler used by WordPress.
s
is the ID of the main text field of the default WordPress search form. You can change this if your form is marked up differently.