WordPress Search Autocomplete using WP REST API v2
<?php
/**
* Enqueue scripts and styles.
*
* @since 1.0.0
*/
function ja_global_enqueues() {
wp_enqueue_style(
'jquery-auto-complete',
'https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.css',
array(),
'1.0.7'
);
wp_enqueue_script(
'jquery-auto-complete',
'https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.min.js',
array( 'jquery' ),
'1.0.7',
true
);
wp_enqueue_script(
'global',
get_template_directory_uri() . '/js/global.min.js',
array( 'jquery' ),
'1.0.0',
true
);
wp_localize_script(
'global',
'global',
array(
'search_api' => home_url( 'wp-json/ja/v1/search' )
)
);
}
add_action( 'wp_enqueue_scripts', 'ja_global_enqueues' );
/**
* WP REST API register custom endpoints
*
* @since 1.0.0
*/
function ja_rest_api_register_routes() {
register_rest_route( 'ja/v1', '/search', array(
'methods' => 'GET',
'callback' => 'ja_rest_api_search',
) );
}
add_action( 'rest_api_init', 'ja_rest_api_register_routes' );
/**
* WP REST API search results.
*
* @since 1.0.0
* @param object $request
*/
function ja_rest_api_search( $request ) {
if ( empty( $request['term'] ) ) {
return;
}
$results = new WP_Query( array(
'post_type' => array( 'post', 'page' ),
'post_status' => 'publish',
'posts_per_page'=> 30,
's' => $request['term'],
) );
if ( !empty( $results->posts ) ) {
return $results->posts;
}
}
/* globals global */
jQuery(function($){
var searchRequest;
$('.search-autocomplete').autoComplete({
minChars: 2,
source: function(term, suggest){
try { searchRequest.abort(); } catch(e){}
searchRequest = $.get( global.search_api, { term: term }, function( res ) {
if ( res !== null ) {
var results = [];
for(var key in res) {
results.push(res[key].post_title)
}
suggest(results);
}
});
}
});
});
<form class="navbar-form" role="search" method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<div class="form-group">
<input type="text" name="s" class="form-control search-autocomplete" placeholder="Search">
</div>
<button type="submit" class="fa fa-search"></button>
</form>