Improve WordPress Search Function

See some great tips and tricks to improve the WordPress search function and better show on your site content for your views and users.

Updated on August 7, 2022
Improve WordPress Search Function

See some great tips and tricks to improve the WordPress search function and better show your site content for your views and users.

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 many posts, WordPress core introduced a patch that would change how search results are sorted.

The changes are as follows:

  • Results with a complete sentence match in the post title are in the first place.
  • Search results that include all search terms in the title but not a complete sentence match are present next.
  • Results are next, including any search terms in the title, but not all search terms or a full sentence match.
  • Finally, search results that include a full sentence match in the post content come last. Within each group, results are further up chronologically by publication date.

Improve WordPress Search Function

Excerpts in search results by WordPress are not precisely significant. Unlike Google, the WordPress search omits emphasis on the keyword if it found matches. 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. This example is a file I’ve created manually, called in/template-parts/post/content-search.php a Twenty Seventeen child theme. This file is a copy thatcontent-excerpt.php exists in the same directory.

Next, look for the file called search.php in the theme’s leading 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 );
}

This function takes the passed content, emphasizes every occurrence of the word(s), and
returns the text. The class that was added to the tag<strong> can be used to style the result further (if you want to).

Adding emphasis on the title to improve the WordPress search function

Improve WordPress Search Function
Improve WordPress Search Function

Now that we’ve gone through the steps to set up your custom template parts adding emphasis to the title is relatively easy.

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

Adding emphasis in the excerpt
Improve WordPress Search Function

You’d expect that adding emphasis to the excerpt can’t be much more complicated than adding it to the title. Sadly, this is not the case. WordPress automatically concatenates a “Continue reading” link to the end with excerpts. You’d be fine as long as the search phrase doesn’t exist in the post’s slug, 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.

You’ll have to overrule some default WordPress behavior to overcome this temporarily.

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(']]>', ']]&gt;', $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:

  1. Login to Google Analytics.
  2. Click on Admin (gear on the bottom-left).
  3. Under View, click on View Settings.
  4. Scroll down until you find the Site Search Tracking toggle and turn it on.
  5. In the Query Parameter field, enter s. This is the default query parameter that is added by WordPress when using the search function.
  6. Click Save

If your website heavily depends on categories and allows users to use them to refine their searches, Google Analytics will also enable you to add tracking on this. For more information on this subject.

Alternatives

Alternatives search function WP sites
Improve WordPress Search Function

Luckily, there are some alternatives to choose from when you want to improve the search function on your website. As we do out in the comments, the plugin Relevanssi tackles most issues with the search and helps you get it up 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 the search even better. Some parts are Typo-tolerance, 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 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 can read, the WordPress search has improved over the years. Despite this, it still lacks in some aspects. You can improve it by adding extra code to your child’s theme or taking it to the next level using external services such as Algolia and Amazon CloudSearch. Good luck!