[Resolved] Search query to find exact words — erica should not return America

Home Forums Support [Resolved] Search query to find exact words — erica should not return America

Home Forums Support Search query to find exact words — erica should not return America

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #476057
    Denise

    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

    #476075
    Denise

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

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.