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. Found issue with this function, if you search for a term that is exactly the same as a navigation menu item it messes the navigation, duplicates the key words inside the menu item along with couple of other issues.

    Any way of getting around this?
    Thank you
    Sibbo

    1. It may be conflicting with the theme. You may have to edit how the style is applied.

  2. it works like a charm. thank you

    1. Good to know!

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

    it works a magic…. muito obrigado.

  4. it messes up links that contain the search terms

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

  6. 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!
[LIMITED TIME]
[LIMITED TIME]
[60% OFF Today!]
[60% OFF Today!]
[50% OFF TODAY!]
[50% OFF TODAY!]
[60% OFF Today!]
[60% OFF Today!]
[50% OFF Today!]
[50% OFF Today!]