I have this code to search trough my custom meta keys in Wordpress. Searching trough the meta key values is going well. Unfortunately when I search on a post title and there is only one result, the same post is displayed 8 times.
How can I prevent duplicate post titles from showing up in search results?
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);
EDIT: Here is the code for my search form, which I also use to search for titles:
<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>