Improve WordPress Search to Make it Search Exact Words.

The native wordpress search, does not look for exact complete words. It means that when you look for ‘Los’ you also get words like ‘lost’ ‘loser’ in search results. I needed a search which could look for exact word in posts. I implemented wordpress search for exact word in post titles using this code in functions.php.

// Search SQL filter for matching against post title only.
function __search_by_title_only( $search, $wp_query )
{
global $wpdb;

if ( empty( $search ) )
return $search; // skip processing - no search term in query

$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}[[:>:]]')";

$searchand = ' AND ';
}

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

return $search;
}

add_filter( 'posts_search', '__search_by_title_only', 1000, 2 );

You can change this to search for exact words in titles plus content both, by modifying the line 18 to
Method 1:

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

The rest of code will remain same. Using the above snippets you will be able to improve wordpress search and make it exact word search.

I have come across another simpler solution, which be helpful, but the snippet posted above can be customized easily as much you need. So I would use method 1.

Method 2:

add_action('pre_get_posts', 'my_make_search_exact', 10);
function my_make_search_exact($query){

    if(!is_admin() && $query->is_main_query() && $query->is_search) :
        $query->set('exact', true);
    endif;

}

If you need to highlight search words, read here. I hope you like these wonderful snippets, happy coding!

Yumna Tatheer

I am a Computer Science graduate and a part time blogger from Lahore, Pakistan. I am a PHP programmer and a wordpress expert.

More Posts

Follow Me:
Facebook