我有这个代码通过Wordpress中的自定义元键进行搜索。通过元键值搜索进展顺利。不幸的是,当我搜索帖子标题并且只有一个结果时,相同的帖子会显示8次。
如何防止重复的帖子标题显示在搜索结果中?
function custom_search_function($pieces) {
// filter to select search query
if (is_search() && !is_admin()) {
global $wpdb;
$custom_fields = array('regio','provincie');
$keywords = explode(' ', get_query_var('s'));
$query = "";
foreach ($custom_fields as $field) {
foreach ($keywords as $word) {
$query .= "((mypm1.meta_key = '".$field."')";
$query .= " AND (mypm1.meta_value LIKE '%{$word}%')) OR ";
}
}
if (!empty($query)) {
// add to where clause
$pieces['where'] = str_replace("((({$wpdb->posts}.post_title LIKE '%", "( {$query} (({$wpdb->posts}.post_title LIKE '%", $pieces['where']);
$pieces['join'] = $pieces['join'] . " INNER JOIN {$wpdb->postmeta} AS mypm1 ON ({$wpdb->posts}.ID = mypm1.post_id)";
//$pieces['groupby'] = "{$wpdb->posts}.ID";
}
}
return ($pieces);
}
add_filter('posts_clauses', 'custom_search_function', 20, 1);
编辑:这是我的搜索表单的代码,我也用它来搜索标题:
<form id="searchform" action="<?php bloginfo('home'); ?>/" method="get">
<input id="s" maxlength="150" name="s" width="150px" "size="20" type="text" value="" class="txt" />
<input name="post_type" type="hidden" value="bewindvoerders" />
<input id="searchsubmit" class="btn" type="submit" value="Search" />
</form>