This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

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 code and be nice ^_^

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.