How to make your WordPress search match Exactly!

Updated on October 16, 2017

This is a common question about WordPress search match exactly, or in other words, asked by my client:

If I search for a term, all kinds of posts are shown which contain the term, for example, If I search for “all on 4 Implant” I also get posts having the terms “all” or “on” or “4” or “Implant”. But I want only posts results with the search term “all on 4 Implant”. Is that possible in any way?

Solution: Yes, It is possible with a tweak in code:

By Altering the WordPress default query

Following are the different techniques to alter the WordPress default query:

  1. the pre_get_posts
  2. the query_posts
  3. the SQL statement filters
  4. the wp_the_query

Above all, the pre_get_posts is the easiest and recommended way to alter the main query. Thanks to Luis Godinho who explains by adding a hook “pre_get_posts” in theme’s functions.php. This hook would be called after the query variable object is created, but before the actual query is run. This hook gives the developer to access the query object by reference.

This class contains a parameter called exact as shown in the below code, which allows to set whether the search query should return results containing exactly the searched terms or, as set by default, matching each words from the search terms. So, to set the search to work in exact mode, insert the below code in your theme’s functions.php file.

add_action( 'pre_get_posts', 'my_search_is_exact', 10 );

function my_search_is_exact( $query ) {
      if ( !is_admin() && $query->is_main_query() && $query->is_search ) {
          $query->set( 'exact', 1 );
      }
}

Now your search will return results if the post title or content matches exactly the searched terms.

But unfortunately, observed that if you have a post title like “all on 4 Implant”, then a search for “Implant” won’t return results in the exact mode! To solve this, the above code is modified as below:

add_action( 'pre_get_posts', 'my_search_is_exact', 10 );

function my_search_is_exact( $query ) {
       if ( !is_admin() && $query->is_main_query() && $query->is_search ) {
            $query->set( 'sentence', 1 );
       }
}

This sentence query parameter is not well documented, but by making this flag to true or 1, would do a phrase search. This should retrieve content inside the post that matches exactly the sentence pattern.

Was this article helpful?

Related Articles

Leave a Comment