Do you want to highlight keywords in WordPress search results within the_except and the_title?
By default, WordPress doesn’t highlight the searched term in search results. This makes it difficult for users to understand the search results.
For example, if we search for anything on Google, Google automatically bolds the searched query which makes it easy to understand and find the relevant results.
So, if you want to highlight the searched query keyword in WordPress search results, you should use the below code snippet.
php
/**
* Highlight Keywords in Search Results within the_excerpt and the_title
*/
function maverick_highlight_keyword_search_page($text)
{
// If the page is search page
if (is_search()) {
// Get the search query.
$searched_keyword = get_query_var('s');
// Get all the keywords of the search.
$keys = explode(" ", $searched_keyword);
// highlight the keywords in the text.
$text = preg_replace('/(' . implode('|', $keys) . ')/iu', '<strong class="searched-keyword">' . $searched_keyword . '</strong>', $text);
}
return $text;
}
add_filter('the_excerpt', 'maverick_highlight_keyword_search_page');
add_filter('the_title', 'maverick_highlight_keyword_search_page');