WordPress search is a nice addition to a site and can help your users find the content their looking for rather than hunt through menus or landing pages.
One problem. WordPress search relevance isn’t that great. There are other search plugin addons that you can install like Relevanssi, which can help things right out of the box. But here are two quick things to change about your default posts search that can help your users find what they are looking for faster.
1. Order by Relevance
The default search query inside of WordPress takes the search term(s) and then applies the following searches based on those terms
- Full sentence matches in post titles.
- All search terms in post titles.
- Any search terms in post titles.
- Full sentence matches in post content.
Each section and any remaining posts are then sorted by date. But when searching the user is most interested in relevance and not particularly about the date.
What you should first do is change the sort or orderby
of the search using the pre_get_posts
action.
// Add to functions.php
add_action( 'pre_get_posts', function( $query ) {
if ( $query->is_search() ) {
$query->set( 'orderby', 'relevance' );
}
} );
2. Combine the search terms
In the search query, WordPress breaks out the different words in your query into an array of terms. ($q[‘search_terms’]) You can get around this by putting quotes around your search terms and then WordPress knows they should be combined, but for most people this is not intuitive.
By combining the search terms from the array you force WordPress to look for the terms together and not separately. This means that if the user is looking for “Privacy updates” you force WordPress to look for posts with both words together instead of posts with the word “privacy” and then posts with the word “updates” which will lead to a much broader search than the user intended.
// Add to functions.php
function combine_blog_search_terms( $search, $wp_query ) {
global $wpdb;
if ( empty( $search ) )
return $search;
$q = $wp_query->query_vars;
$n = !empty( $q['exact'] ) ? '' : '%';
$search = $searchand = '';
// If the search_terms array is bigger than 1 combine the terms
if (is_array($q['search_terms']) && count($q['search_terms']) > 1){
$q['search_terms'] = implode(' ', $q['search_terms']);
}
foreach ( (array) $q['search_terms'] as $term ) {
$term = esc_sql( $wpdb->esc_like( $term ) );
$search .= "{$searchand}($wpdb->posts.post_title REGEXP '[[:<:]]{$term}[[:>:]]') OR ($wpdb->posts.post_content 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', 'combine_blog_search_terms', 500, 2 );
You can add a conditional to only run the combined search terms when NOT in the admin, but what I have found is that it makes the admin post search much more relevant as well.