Snippet: Highlight Searched Text In Search Results

Add following snippet to your “functions.php”

Snippet

add_filter('the_content', 'highlight_search_text', 99);
add_filter('the_title', 'highlight_search_text', 99);
function highlight_search_text($title) {
	if(is_search()) {
		$keys= explode(" ",get_search_query());
		return preg_replace('/('.implode('|', $keys) .')/iu','<strong class="search-excerpt">\0</strong>',$title);
	}
	return $title;
}

Add following css style to your “style.css”

strong.search-excerpt { background: yellow; }

Result

Searching “Hello” results in

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>