wordpress snippets last updated   : August 18, 2014
we now have 638 snippets

Highlight keywords in search results within the_excerpt and the_title

wordpress snippet

I whipped up this little snippet that you can add to the functions.php of your wordpress theme to highlight keywords in search results for the_excerpt and the_title. A few highlight search results snippets floating around including a great one by Michael Martin. However they require you edit template files so this is my take on Michaels Idea.

snippet :  PHPcopy
function wps_highlight_results($text){
     if(is_search()){
     $sr = get_query_var('s');
     $keys = explode(" ",$sr);
     $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text);
     }
     return $text;
}
add_filter('the_excerpt', 'wps_highlight_results');
add_filter('the_title', 'wps_highlight_results');
source →

Did you like this post? If so please share it with your friends. Thanks!

  • storetext

    Thank you very much for this snippet. I have found a small issue with it though — it de-capitalizes the search term in the search results.

    For example, if I have a post titled “Include password protected posts” and then search for “include”, the title of my post in the search results will be displayed as “include password protected posts”.

    Any idea how this could be fixed?

    • http://twitter.com/harrywlove Harry William Love

      Change the replacement string from

      ''.$sr.''

      to

      '$1'

  • Ahmed Badran

    i have a function that limit my excerpt , how can i do that with it ?

jqsnipp.com | we just launched jquery snippets website