How to improve WordPress search
The default WordPress search functionality is certainly lacking in areas. Although changes were made in 2013 to improve it, there are still a few areas where WordPress could use some help. It is, however, relatively easy to improve WordPress search by adding a few pieces of code. Here, I’ll list some of the methods you could use to make WordPress search better.
Sort by relevance
In older versions of WordPress, search results were sorted by date and not much else. Because this is (at the very least) annoying for websites with a lot of posts, WordPress core introduced a patch that would change the way search results are sorted.
The changes are as followed:
- Results with a full sentence match in the post title are listed first.
- Search results that include all search terms in the title, but not a full sentence match, are listed next.
- Results including any search terms in the title, but not all search terms or a full sentence match, are listed next.
- Finally, search results that include a full sentence match in the post content come last. Within each group, results are further sorted chronologically by publication date.
Improving the interface
Excerpts in search results by WordPress are not exactly great. Unlike Google, the WordPress search omits emphasis of the keyword if it found matches. Luckily, you can alter parts of the search results and add this feature.
Preparing your theme
In your theme, look for the file that outputs the search results. In this example, it’s a file that I’ve created manually, called /template-parts/post/content-search.php
in a Twenty Seventeen child theme. This file is a copy of content-excerpt.php
that exists in the same directory.
Next, look for the file called search.php
in the theme’s main directory and look for the following line of code:
get_template_part( 'template-parts/post/content', 'excerpt' );
Change this to the following:
get_template_part( 'template-parts/post/content', 'search' );
By making these changes, you’ll ensure that WordPress will use your custom template instead of the default one. Time to add the actual code that will be doing the emphasizing!
Open up functions.php
and add the following function:
/**
* Adds emphasis to the parts passed in $content that are equal to $search_query.
*
* @param $content The content to alter.
* @param $search_query The search query to match against.
*
* @return string The emphasized text.
*/
function emphasize( $content, $search_query ) {
$keys = array_map( 'preg_quote', explode(" ", $search_query ) );
return preg_replace( '/(' . implode('|', $keys ) .')/iu', '<strong class="search-excerpt">\0</strong>', $content );
}
What this function does, is taking the passed content and emphasize every occurrence of the word(s) passed in $search_query
and return the text. The class that was added to the <strong>
tag can be used to further style the end result (if you want to).
Adding emphasis in the title
Now that we’ve gone through the steps to setup your custom template parts adding emphasis in the title is relatively easy to do.
Go into your newly created content-search.php
and find the line that looks like:
the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' );
and replace it with the following:
$title = emphasize( get_the_title(), get_search_query() );
echo sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">%s', esc_url( get_permalink() ), $title ) . '</a></h2>';
That’s all there is to it!
Adding emphasis in the excerpt
You’d expect that adding emphasis to the excerpt can’t be much harder than adding it to the title. Sadly, this is not the case. With excerpts, WordPress automatically concatenates a “Continue reading” link to the end. You’d be fine as long as the search phrase doesn’t exist in the slug of the post, but most of the time if you’re looking for specific keywords, it will be present in the slug. This results in a broken “Continue reading” link.
To overcome this, you’ll have to temporarily overrule some default WordPress behavior.
First, add the following to your functions.php
:
/**
* Creates a custom read more link.
*
* @return string The read more link.
*/
function modify_read_more_link() {
return ' <a class="more-link" href="' . get_permalink() . '">Continue reading</a>';
}
The above code will be called to ensure we have a workable “Read more” link.
This part hooks into the function that creates the actual excerpt and adds our emphasis and custom “Read more” link.
/**
* Allows for excerpt generation outside the loop.
*
* @param string $text The text to be trimmed
* @return string The trimmed text
*/
function custom_trim_excerpt( $text = '' ) {
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$excerpt_length = apply_filters('excerpt_length', 55);
$trimmed = wp_trim_words( $text, $excerpt_length, '' );
if ( is_search() ) {
$trimmed = emphasize( $trimmed, get_search_query() );
}
return $trimmed . modify_read_more_link();
}
add_filter('wp_trim_excerpt', 'custom_trim_excerpt');
Sadly, there’s no elegant alternative for this. Hopefully, someday, a filter will be created that can be called instead of having to overrule large portions of the trim function.
Tracking searches
There are a few options to track the search queries that visitors have entered, but we recommend using Google Analytics for this. To get started with tracking searches, please go through the following steps:
- Login to Google Analytics.
- Click on Admin (gear on the bottom-left).
- Under View, click on View Settings
- Scroll down until you find the Site Search Tracking toggle and turn it on.
- In the Query Parameter field, enter
s
. This is the default query parameter that is added by WordPress when using the search function. - Click Save
If your website is heavily dependent on categories and allows users to use them to refine their searches, Google Analytics gives you the ability to add tracking on this too. For more information on this subject, you can read Google’s documentation on search tracking in this article.
Alternatives
Luckily, there are some alternatives to choose from when you want to improve the search function on your website. As pointed out in the comments, the plugin Relevanssi tackles most issues with the search and helps you get started quickly and easily.
If your website has grown a lot and you want to supercharge your search even more, it might be wise to look at a few, more complex alternatives. One that we use at Yoast is Algolia. This platform contains a ton of features to make search even better. Some features are: Typo-tolerance, support for synonyms, filters, and support for 100+ languages. It also includes integrations with WordPress!
Another alternative is Amazon CloudSearch. It offers similar features to Algolia, and you can enable autoscaling if you think your website needs it. However, ACS does not provide you with an integration out of the box, so you’ll have to write your implementation or look for a WordPress plugin in the Plugin Directory. At the time of writing, there are only two plugins present; CloudSearch and Lift.
Yes, you can improve WordPress search
As you could read, the WordPress search has improved over the years. Despite this, it still lacks in some aspects. Luckily you can improve it by adding some extra code in your child theme or take it to the next level by using external services such as Algolia and Amazon CloudSearch. Good luck!
Read more: Internal search: why and how »
Coming up next!
-
Event
WordCamp Netherlands 2024
November 29 - 30, 2024 Team Yoast is at Sponsoring WordCamp Netherlands 2024! Click through to see who will be there, what we will do, and more! See where you can find us next » -
SEO webinar
Webinar: How to start with SEO (November 19, 2024)
19 November 2024 Learn how to start your SEO journey the right way with our free webinar. Get practical tips and answers to all your questions in the live Q&A! All Yoast SEO webinars »
17 Responses to How to improve WordPress search