我一直在尝试在我的 WordPress 中添加自动完成功能,但没有成功。
在我的functions.php中:
// Loads files with autocomplete
wp_register_script( 'jquery-ui', get_template_directory_uri() . '/js/jquery-ui.min.js', array( 'jquery' ) );
wp_enqueue_script( 'jquery-ui');
wp_register_style( 'jquery-style', get_template_directory_uri() . '/js/jquery-ui.css' );
wp_enqueue_style( 'jquery-style' );
wp_register_script( 'autocomplete-ui', get_template_directory_uri() . '/js/autocomplete.js', array( 'jquery') );
wp_localize_script( 'autocomplete-ui', 'autocomplete-object', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'autocomplete-ui');
在我的 autocomplete.js 中
function ($) {
'use strict';
$(function() {
$( "#busca" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: 'GET',
dataType: "json",
data: {
action: "autocompleteCallback",
term: request.term
},
success: function (data) {
}, }); } }); }); }(jQuery);
回到我的functions.php:
function acCallback() {
global $wpdb;
$search = $_REQUEST['term'];
$query = $wpdb->get_results( "SELECT $wpdb->postmeta.meta_value FROM $wpdb->postmeta WHERE postmeta.meta_value LIKE \'' . $search . '%\' AND post_type = \'NAME OF CUSTOM POST TITLE \'
AND $wpdb->postmeta.meta_key = 'produto'" );
$tab = array();
foreach ($query->posts as $p):
$tab[] =array('value'=>$p->postmeta.meta_value);
endforeach;
echo(json_encode($tab));
exit;
}
add_action( 'wp_ajax_autocompleteCallback', 'acCallback' );
add_action( 'wp_ajax_nopriv_autocompleteCallback', 'acCallback' );
我的自动完成中没有出现任何内容...我的错误是什么?感谢您的帮助
我明白了!我必须做出一些改变,但最主要的是:
在我的 autocomplete.js 中
....
success: function (data) {
response($.map(data, function(item) {
return {
value: item.meta_value,
id :item.meta_id
};
}));
};
在我的functions.php中:
global $wpdb;
$search = $_GET['term'];
$query = $wpdb->get_results( "SELECT DISTINCT meta_id, meta_value FROM wp_postmeta WHERE meta_key='NAME OF META KEY' AND meta_value LIKE '".$search."%' " );
$suggestions = array();
foreach($query as $row) {
array_push($suggestions, array(
'meta_value' => $row->meta_value,
'meta_id' => $row->meta_id
)
);
}
echo json_encode( $suggestions );
exit();