How To Highlight Search Results In WP

Quick Summary

  • Filter the_content, the_excerpt and the_title to wrap searched words in a search-highlight span on search results pages.
  • The highlight stays invisible until you style .search-highlight in your stylesheet, for example with a yellow background color.
  • Regex characters in search words can break the pattern unless run through preg_quote(), and spans inserted inside HTML tags can break markup.

On a WordPress search results page, this snippet wraps every occurrence of the searched words in <span class="search-highlight">, so you can style the matches and make them easy to spot. Add it to your theme’s functions.php file, ideally in a child theme.

PHP
function themename_highlight_search_results($text){
    if(is_search()){
        $pattern = '/('. join('|', explode(' ', get_search_query())).')/i';
        $text = preg_replace($pattern, '<span class="search-highlight">\0</span>', $text);
    }
    return $text;
}
add_filter('the_content', 'themename_highlight_search_results');
add_filter('the_excerpt', 'themename_highlight_search_results');
add_filter('the_title', 'themename_highlight_search_results');

How it works

  • The function is attached to three filters, the_content, the_excerpt and the_title, so it runs on post content, excerpts and titles.
  • is_search() limits it to search results pages; everywhere else the text is returned unchanged.
  • get_search_query() returns the search terms. explode() splits them at each space and join() builds a pattern such as /(wordpress|theme)/i, where i makes the match case-insensitive.
  • preg_replace() wraps each match in the span. \0 stands for the matched text, so its original capitalization is kept.

The highlight is invisible until you style it: add a rule for .search-highlight to your stylesheet, for example with a yellow background color.

Limitations

  • The search words go into the pattern as typed. Characters with a special meaning in regular expressions, such as /, ( or +, can break the pattern. Running each word through preg_quote() avoids that.
  • The replacement also runs inside HTML tags. If a search word appears in a class name, a link or an image attribute in the content, a span can be inserted there and break the markup.
  • The the_title filter is used in other places too, such as menus and widgets, so matching titles there are highlighted on search pages as well.
Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More