Skip to content

Instantly share code, notes, and snippets.

@zorzv
Created February 3, 2017 19:15
Show Gist options
  • Save zorzv/a7b4f69231f134aa56824dd139f0030d to your computer and use it in GitHub Desktop.
Save zorzv/a7b4f69231f134aa56824dd139f0030d to your computer and use it in GitHub Desktop.
Autocomplete Taxonomy Terms in Wordpress
//Custom Autocomplete
add_action('wp_ajax_nopriv_get_listing_names', 'ajax_listings');
add_action('wp_ajax_get_listing_names', 'ajax_listings');
function ajax_listings() {
global $wpdb; //get access to the WordPress database object variable
//get names of all taxonomy terms
$name = '%'.$wpdb->esc_like(stripslashes($_GET['name'])).'%'; //escape for use in LIKE statement
$sql = "SELECT term.term_id as id, term.name as post_title, term.slug as guid, tax.taxonomy FROM $wpdb->term_taxonomy tax
LEFT JOIN $wpdb->terms term ON term.term_id = tax.term_id WHERE 1 = 1
AND term.name LIKE %s
AND tax.taxonomy = 'country'
ORDER BY tax.count DESC
";
$sql = $wpdb->prepare($sql, $name);
$wpdb->show_errors();
$results = $wpdb->get_results($sql);
//$wpdb->print_error();
if (count($results)> 0){ //check if the result is empty
//copy the titles to a simple array
$titles = array();
foreach( $results as $r )
$titles[] = addslashes($r->post_title);
echo json_encode($titles); //encode into JSON format and output
}
else {
$message = "No results found";
echo json_encode($message);
}
die();
}
//enqueue custom JS
function search_js() {
//load Pixabay's AutoComplete
wp_enqueue_style('autocomplete_css', get_stylesheet_directory_uri().'/css/jquery.auto-complete.css');
wp_enqueue_script('jquery-autocomplete', get_stylesheet_directory_uri().'/js/jquery.auto-complete.min.js', array('jquery'));
//load your JS custom file
wp_enqueue_script('mysite-js', get_stylesheet_directory_uri().'/js/search.autocomplete.js', array('jquery', 'jquery-autocomplete'));
wp_localize_script( 'mysite-js','myAjaxData', array( 'ajaxurl' => admin_url('admin-ajax.php') )
);
}
add_action('wp_enqueue_scripts', 'search_js');
jQuery(document).ready(function($) {
$('#s').autoComplete({
delay: 10,
cache: true,
minChars: 2,
source: function(name, response) {
$.ajax({
type: 'GET',
dataType: 'json',
url: myAjaxData.ajaxurl,
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
},
error: function (response) {
}
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment