Highlight keywords in search results within the_excerpt and the_title

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.

function wps_highlight_results($text){
     if(is_search()){
         $sr = get_query_var('s');
         $keys = explode(" ",$sr);
         $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong>'.$sr.'</strong>', $text);
     }
     return $text;
}
add_filter('the_excerpt', 'wps_highlight_results');
add_filter('the_title', 'wps_highlight_results');
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s