【发布时间】:2015-12-20 00:08:05
【问题描述】:
我有一个用户可以搜索产品的 Wordpress ajax 搜索字段。我也希望能够按产品类别搜索。 “Whats new”、“限量版”等。如何查询和显示类别名称?
我还需要用户能够按位置名称进行搜索,并在单击时直接进入位置页面。因此,如果他们搜索“Walmart”或“Target”,链接将始终转到位置页面。该位置不会是分类法,所以我猜这必须用所有位置名称进行硬编码,这很好。我如何将其硬编码到查询中?
<?php
/*
** Custom search ajax
*/
add_action('wp_ajax_custom-search', 'search_ajax');
add_action('wp_ajax_nopriv_custom-search', 'search_ajax');
function search_ajax() {
if($_GET['s'] === '') {
wp_send_json(array(
'results' => [],
));
}
else {
$query = new WP_Query( array('s' => $_GET['s'], 'post_type' => array('product', 'tutorial') ) );
$query2 = new WP_Query( array('tag' => sanitize_title_with_dashes($_GET['s']) . ',' . sanitize_title_with_dashes(preg_replace('/s$/i', '', $_GET['s'])) . ',' . sanitize_title_with_dashes(preg_replace('/es$/i', '', $_GET['s'])) , 'post_type' => array('product', 'tutorial') ) );
$wp_query = new WP_Query();
$wp_query->posts = array_merge( $query->posts, $query2->posts );
$wp_query->post_count = $query->post_count + $query2->post_count;
wp_send_json(array(
'results' => array_map(function($p) { return array( 'title'=>get_the_title($p),'uri'=>get_permalink($p),'category'=>get_the_category($p->ID, 'search_category'),'postType'=>get_post_type($p),'thumb'=>get_the_post_thumbnail($p->ID,'medium')); }, $wp_query->posts)
));
}
}
?>
【问题讨论】: