Autocomplete WP
function load_scripts() {
wp_register_script( 'auto-complete-js', get_template_directory_uri() . '/js/jquery.auto-complete.min.js', array('jquery') );
wp_enqueue_script( 'auto-complete-js' );
}
//https://goodies.pixabay.com/jquery/auto-complete/demo.html
//https://github.com/Pixabay/jQuery-autoComplete
add_action('wp_ajax_nopriv_get_listing_names', 'ajax_listings');
add_action('wp_ajax_get_listing_names', 'ajax_listings');
// function apply_highlight($a_json, $parts) {
// $p = count($parts);
// $rows = count($a_json);
// for($row = 0; $row < $rows; $row++) {
// $label = $a_json[$row]["label"];
// $a_label_match = array();
// for($i = 0; $i < $p; $i++) {
// $part_len = mb_strlen($parts[$i]);
// $a_match_start = mb_stripos_all($label, $parts[$i]);
// foreach($a_match_start as $part_pos) {
// $overlap = false;
// foreach($a_label_match as $pos => $len) {
// if($part_pos - $pos >= 0 && $part_pos - $pos < $len) {
// $overlap = true;
// break;
// }
// }
// if(!$overlap) {
// $a_label_match[$part_pos] = $part_len;
// }
// }
// }
// if(count($a_label_match) > 0) {
// ksort($a_label_match);
// $label_highlight = '';
// $start = 0;
// $label_len = mb_strlen($label);
// foreach($a_label_match as $pos => $len) {
// if($pos - $start > 0) {
// $no_highlight = mb_substr($label, $start, $pos - $start);
// $label_highlight .= $no_highlight;
// }
// $highlight = '<span class="hl_results">' . mb_substr($label, $pos, $len) . '</span>';
// $label_highlight .= $highlight;
// $start = $pos + $len;
// }
// if($label_len - $start > 0) {
// $no_highlight = mb_substr($label, $start);
// $label_highlight .= $no_highlight;
// }
// $a_json[$row]["label"] = $label_highlight;
// }
// }
// return $a_json;
// }
function ajax_listings() {
global $wpdb;
$name = $wpdb->esc_like($_GET['term']).'%';
$sql = "select id,post_title
from $wpdb->posts
where post_title like %s
and post_type='city' and post_status='publish'";
$sql = $wpdb->prepare($sql, $name);
$results = $wpdb->get_results($sql);
$a_json_row = array();
foreach( $results as $r ) {
$a_json_row[] = array(
'id' => $r->id,
'value' => $r->post_title,
'label' => $r->post_title
);
}
$json = json_encode($a_json_row);
echo $json;
die();
}
<?php wp_footer() ?>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.min.js"type="text/javascript"></script>
$("#city").autocomplete({
source: "/wp-admin/admin-ajax.php?action=get_listing_names",
minLength: 2,
select: function(event, ui) {
var url = ui.item.id;
if(url != '#') {
location.href = '/?post_type=city&p=' + url;
}
},
html: true, // optional (jquery.ui.autocomplete.html.js required)
// optional (if other layers overlap autocomplete list)
open: function(event, ui) {
$(".autocomplete").css("z-index", 1000);
}
});