Want to know what WordPress Theme a site is using? Check Out Now!

Highlight Keywords in WordPress Search Results within the_excerpt and the_title

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.

 * 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');

Leave a Reply

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