Add class to search terms for highlighting in WordPress search results

When a user searches your WordPress site it’s nice to give them some feedback on the term they’ve just search, this function will add a class to the search terms you can then use css to highlight the search results.

function wptx_highlight_results($text){
     $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', 'wptx_highlight_results');
add_filter('the_content', 'wptx_highlight_results');
add_filter('the_title', 'wptx_highlight_results');



A geek who likes to cook with wp ingredients!

Leave a Reply

Your email address will not be published. Required fields are marked *