X

Highlight keywords in search results within the_excerpt and the_title

Enigma Review - service options

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.



Code Snippet:


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');

Comments  Leave a Reply

  1. johannes khampepe December 29, 2016 at 1:07 pm

    it works a magic…. muito obrigado.

  2. it messes up links that contain the search terms

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

  4. 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?

    1. Harry William Love April 2, 2013 at 3:24 pm

      Change the replacement string from

      ''.$sr.''

      to

      '$1'

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!