How To Highlight Search Results In WP

Share Now

Add this code in functions.php file


function themename_highlight_search_results($text){
    if(is_search()){
        $pattern = '/('. join('|', explode(' ', get_search_query())).')/i';
        $text = preg_replace($pattern, '<span class="search-highlight">\0</span>', $text);
    }
    return $text;
}
add_filter('the_content', 'themename_highlight_search_results');
add_filter('the_excerpt', 'themename_highlight_search_results');
add_filter('the_title', 'themename_highlight_search_results');

Picture of Nahid Mahamud

Nahid Mahamud

Web Developer | Graphic Designer | WordPress & Woo-commerce Expert