Site logo

Archived topic

Search query to find exact words -- erica should not return America

1 reply · Started by Denise on January 20, 2018

Viewing posts 1–2 of 2

Hi GP Friends,
I would like to modify the WP search query so that it looks for exact word matches. I understand this is tricky and requires regular expressions. I am trying some code (pasted below) and put it in functions.php of the child theme. But it didn't change the search. Can you tell me if it needs to be using a GP hook or filter? Or am I missing something in the code?

Many thanks,
Denise

add_filter('posts_search', 'my_search_is_exact', 20, 2);
function my_search_is_exact($search, $wp_query){

global $wpdb;

if(empty($search))
return $search;

$q = $wp_query->query_vars;
$n = !empty($q['exact']) ? '' : '%';

$search = $searchand = '';

foreach((array)$q['search_terms'] as $term) :

$term = esc_sql(like_escape($term));

$search.= "{$searchand}($wpdb->posts.post_title REGEXP '[[:<:]]{$term}[[:>:]]') OR ($wpdb->posts.post_content REGEXP '[[:<:]]{$term}[[:>:]]')";

$searchand = ' AND ';

endforeach;

if(!empty($search)) :
$search = " AND ({$search}) ";
if(!is_user_logged_in())
$search .= " AND ($wpdb->posts.post_password = '') ";
endif;

return $search;

}

[source of code: https://wordpress.stackexchange.com/questions/177183/make-a-wp-query-search-match-exactly-the-search-term%5D

I've decided to use the plugin Custom Views Pro, which has a keyword search.
You may close this ticket.

This archived topic is closed to new replies.