我试图实现一个自动完成搜索,但我有一些困难,使其正常工作。
当我在搜索中输入一些单词时,自动完成搜索不会过滤结果,并且总是显示我的所有帖子。所以它根本不搜索。。。
我还很难理解显示自定义结果的方式,例如tumbnail、标题和每个已查找帖子的类别。
这里是我的脚本:
require_once ($admin_path . "search_autocomplete.php");
function search_ac_init() {
wp_enqueue_script( \'search_ac\', get_template_directory_uri() . \'/js/search_ac.js\', array(\'jquery\',\'jquery-ui-autocomplete\'),null,true);
wp_localize_script( \'search_ac\', \'MyAcSearch\', array(\'url\' => admin_url( \'admin-ajax.php\' )));
}
add_action( \'init\', \'search_ac_init\' );
在search\\u autocomplete中。php:
<?php
add_action( \'wp_ajax_search_autocomplete\', \'search_autocomplete\' );
add_action( \'wp_ajax_nopriv_search_autocomplete\', \'search_autocomplete\' );
function search_autocomplete(){
$posts = get_posts( array(
\'search\' =>$_REQUEST[\'term\'],
) );
$suggestions=array();
global $post;
$args = array(\'post_type\' => array(\'post\', \'portfolio\'), \'posts_per_page\' => 10, \'post_status\' => \'publish\');
$myposts = get_posts($args);
foreach ($myposts as $post): setup_postdata($post);
$suggestion = array();
$suggestion[\'label\'] = esc_html($post->post_title);
$suggestion[\'link\'] = get_permalink();
$suggestions[]= $suggestion;
?>
//<a class="link" href="<?php echo get_permalink(); ?>");>
//<div class="img">
//<img class="<?php echo wp_get_attachment_url( get_post_thumbnail_id()); ?>"/ >
//</div>
//<div class="title"><?php echo the_title(); ?></div>
//<div class="post"><?php echo $post_type; ?></div>
//</a>
// I want to display like above
<?php
endforeach;
$response = $_GET["callback"] . "(" . json_encode($suggestions) . ")";
echo $response;
exit;
}
?>
和search\\u ac.js:
jQuery(document).ready(function ($){
var acs_action = \'search_autocomplete\';
$("input#search").autocomplete({
minLength: 3,
source: function(req, response){
$.getJSON(MyAcSearch.url+\'?callback=?&action=\'+acs_action, req, response);
},
select: function(event, ui) {
window.location.href=ui.item.link;
},
open: function(event,ui){
var len = $(\'.ui-autocomplete > li\').length;
var ImgAtocompleteWidth = 60*(1/ratio);
$(".image-autocomplete").width(ImgAtocompleteWidth);
$(\'#input-count\').show();
$(\'#clearInput\').show();
if (len==1) {
$(\'#input-count\').html(len+\' result\');
} else {
$(\'#input-count\').html(len+\' results\');
}
},
close: function( event, ui ){
$(\'#input-count\').html(\'\')
.hide();
$(\'#clearInput\').hide(100);
if( $(\'#noMatches\').is(\':visible\') ) {
$(\'#clearInput\').show(100);
}
},
focus: function (event, ui) {
titleinput = ui.item.value;
ui.item.value= $.trim(titleinput);
$( "input#search" ).val( ui.item.value );
$(\'#input-count\').show();
return false;
},
}).focus(function(event, ui){
$(this).autocomplete("search");
})
});