Skip to content

Instantly share code, notes, and snippets.

@jaredatch
Last active July 3, 2023 23:10
Show Gist options
  • Star 51 You must be signed in to star a gist
  • Fork 20 You must be signed in to fork a gist
  • Save jaredatch/79e57c68438841b6c09b3ad4c12600f6 to your computer and use it in GitHub Desktop.
Save jaredatch/79e57c68438841b6c09b3ad4c12600f6 to your computer and use it in GitHub Desktop.
WordPress Search Autocomplete using admin-ajax.php
<?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(
'ajax' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action( 'wp_enqueue_scripts', 'ja_global_enqueues' );
/**
* Live autocomplete search feature.
*
* @since 1.0.0
*/
function ja_ajax_search() {
$results = new WP_Query( array(
'post_type' => array( 'post', 'page' ),
'post_status' => 'publish',
'nopaging' => true,
'posts_per_page'=> 100,
's' => stripslashes( $_POST['search'] ),
) );
$items = array();
if ( !empty( $results->posts ) ) {
foreach ( $results->posts as $result ) {
$items[] = $result->post_title;
}
}
wp_send_json_success( $items );
}
add_action( 'wp_ajax_search_site', 'ja_ajax_search' );
add_action( 'wp_ajax_nopriv_search_site', 'ja_ajax_search' );
/* globals global */
jQuery(function($){
var searchRequest;
$('.search-autocomplete').autoComplete({
minChars: 2,
source: function(term, suggest){
try { searchRequest.abort(); } catch(e){}
searchRequest = $.post(global.ajax, { search: term, action: 'search_site' }, function(res) {
suggest(res.data);
});
}
});
});
<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>
@abdullah1908
Copy link

Hi,
Thanks for the useful gist.
I am having the following error. Please see the screenshot. Your quick response would be much appreciated.
autoComplete-console-error
Thanks in advance.

@mrcodefinger
Copy link

@baranovsky-s
remove $items[] = $result->post_title; in line 61 and replace it with $items[] = get_permalink($result->ID);

@abhijitdmt
Copy link

where is global.min.js ?? thanks

Rename it global.js and upload it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment