我已经在woocommerce网站上进行了自定义搜索查询。 一切都很好看。但是当我搜索类似sku号码的东西时,会出现两个搜索结果。
示例搜索结果
示例 - http://bxcell.iteratemarketing.com/?s=BE0204&post_type=product
这是我的代码
add_filter('the_posts', 'woo_custom_fields_query');
function woo_custom_fields_query($posts, $query = false) {
if (is_search()){
$noIds = array(0);
foreach($posts as $post){
$noIds[] = $post->ID;
}
$mPosts = get_post_by_custom_field(get_search_query(), $noIds);
if ($mPosts){
foreach($mPosts as $product_id){
$posts[] = get_post($product_id->post_id);
}
}
return $posts;
}
return $posts;
}
function get_post_by_custom_field($qrval, $noIds) {
global $wpdb, $wp_query;
$pstArr = array();
$noIdsQrl = implode(",", $noIds);
$vrvspsts = $wpdb->get_results(
"
SELECT p.post_parent as post_id FROM $wpdb->posts as p
join $wpdb->postmeta pm
on p.ID = pm.post_id
and pm.meta_value LIKE '%$qrval%'
join $wpdb->postmeta visibility
on p.post_parent = visibility.post_id
and visibility.meta_key = '_visibility'
and visibility.meta_value <> 'hidden'
where 1
AND p.post_parent <> 0
and p.ID not in ($noIdsQrl)
and p.post_status = 'publish'
group by p.post_parent
"
);
foreach($vrvspsts as $post){
$noIds[] = $post->post_id;
}
$noIdsQrl = implode(",", $noIds);
$rglprds = $wpdb->get_results(
"SELECT p.ID as post_id FROM $wpdb->posts as p
join $wpdb->postmeta pm
on p.ID = pm.post_id
AND pm.meta_value LIKE '%$qrval%'
join $wpdb->postmeta visibility
on p.ID = visibility.post_id
and visibility.meta_key = '_visibility'
and visibility.meta_value <> 'hidden'
where 1
and (p.post_parent = 0 or p.post_parent is null)
and p.ID not in ($noIdsQrl)
and p.post_status = 'publish'
group by p.ID
");
$pstArr = array_merge($vrvspsts, $rglprds);
$wp_query->found_posts += sizeof($pstArr);
return $pstArr;
}
提前致谢!
答案 0 :(得分:1)
我认为,你的两个查询逻辑存在问题。您从两个结果中获得了合并数组中的重复post ID。
$pstArr = array_unique(array_merge($vrvspsts, $rglprds));