0

I'm facing a challenge with a WordPress project and I would appreciate the community's help in solving it.

The issue lies with the search functionality. When customers type in a search term, such as "tooth," WordPress returns results that contain words like "toothmed" and "yellowtooth." However, I would like the search to be more precise and return only results with the exact term entered, not words that contain the term as part of them.

I believe this can be addressed using a hook that handles search results before they are sent to the database. I need this hook to remove wildcard characters (%) before and after the search terms, ensuring that results are displayed only when the searched term is bounded by word boundaries.

I appreciate any help or guidance you can provide to solve this issue. If anyone has experience with hooks or has encountered a similar situation, please share your expertise.

Thank you in advance for your cooperation!

2
  • "REMEMBERING THAT IF I SEARCH FOR 'TOOTH' AND IT RETURNS 'YELLOW TOOTH' 'TOOTH YELLOW' THOSE ARE DESIRED RESULTS, BECAUSE THE TERMS ARE SEPARATED AND AS IT FOUND A RESULT FOR THE TERMS THIS SCENARIO SATISFIES ME." Commented May 4 at 21:52
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
    – Community Bot
    Commented May 5 at 16:54

1 Answer 1

0

You could try something like this below. Basically, if we are performing a search and it is the main_query (the query that generates the page results) ignore the default search and perform an exact match via the query_where

function custom_product_search_exact_match( $query ) {
    global $wpdb;

    if ( is_search() && is_main_query() && !empty( $query->query_vars['s'] ) ) {
        $search_term = $query->query_vars['s'];
        $query->query_vars['s'] = '';

        $query->query_where .= " AND ($wpdb->posts.post_title = '$search_term')";
    }

    return $query;
}
add_filter( 'pre_get_posts', 'custom_product_search_exact_match' );

Not the answer you're looking for? Browse other questions tagged or ask your own question.