Monday, October 1, 2012

Highlight keywords in search results within the_excerpt and the_title

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 class="search-excerpt">'.$sr.'</strong>', $text);
     }
     return $text;
}
add_filter('the_excerpt', 'wps_highlight_results');
add_filter('the_title', 'wps_highlight_results');

No comments:

Post a Comment