Select Page

Do you want to highlight the keywords the user searched for in the title and excerpt of the search results? You can highlight keywords in the search pages in WordPress just like Google does.

Add this code to your functions.php file:

function highlight_keywords_in_text($text){
	if( is_search() ){
		$search_query = get_query_var('s'); // Get the search query.
		$keywords = explode(" ", $search_query); // Get all the keywords of the search.
		// Put the keywords in the text inside <strong> tags to bold them.
		$text = preg_replace('/('.implode('|', $keywords) .')/iu', '<strong class="keyword-highlight">\0</strong>', $text);
	return $text;
add_filter('the_title', 'highlight_keywords_in_text');
add_filter('the_excerpt', 'highlight_keywords_in_text');

The above function is called on the the_title and the_excerpt functions filters. It first checks if this is the search page. If it is, then it creates an array of keywords from the search query string. It then replaces all keywords inside the text of the_title and the_excerpt with <strong> tags. The <strong> tags will bold the keywords.

If you want, you can target the ‘keyword-highlight’ class in your CSS to customize the style of the highlighted keywords.

You could use something like this:

.keyword-highlight {background: #FBFF12;}