X

Highlight Keywords in Search Results within the_excerpt and the_title

Snippets by IsItWP

Highlighting the keywords in search results within the post title and excerpt will let your users know what they’ll find in the article.

Instructions: Add to the following code to the functions.php of your WordPress theme.

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

You may also enjoy replacing keywords in the_content and the_excerpt.

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!