WP_Query search for whole words

I’m searching for science related terms. Here’s what I need my query to do. If someone searches ‘bio’, they should not get results for terms ‘biology’ but they should for ‘bio science’. I need the query to return results for the whole word. Any suggestions are appreciated. Thanks!

Here is my code:

    $queryArgs = array(
    'post_type' => 'faculty',
    'posts_per_page' => -1,
    'meta_query' => array(
        'relation' => 'OR',
        array( 
            'key' => 'proposed_keywords', // name of custom field
            'value' => $keyword, // matches exaclty "123", not just 123. This prevents a match for "1234"
            'compare' => 'LIKE'
        )
    )
 );

2 Answers
2

You’re gonna need regular expressions to accomplish that.

First of all, you need to change 'LIKE' to 'RLIKE' (or 'REGEXP').

Second, replace $keyword in 'value' with a regex that involves word boundaries.

Like so:

  $queryArgs = array(
    'post_type' => 'faculty',
    'posts_per_page' => -1,
    'meta_query' => array(
        'relation' => 'OR',
        array( 
            'key' => 'proposed_keywords', // name of custom field
            'value' => "[[:<:]]$keyword[[:>:]]", // matches exaclty "123", not just 123. This prevents a match for "1234"
            'compare' => 'RLIKE'
        )
    )
  );

Leave a Comment