Snippets: Highlight Search Terms

The following code will add a span with the "search-term" class to your search results which you can use to better highlight search terms on your WordPress site using Total.

function myprefix_highlight_search( $output ) {
	if ( is_search() && is_main_query() && in_the_loop() ) {
		$keys   = explode( " ", get_search_query() );
		$output = preg_replace( '/('.implode('|', $keys ) .')/iu', '<strong class="search-term">\0</strong>', $output );
	}
	return $output;
}
add_filter( 'wpex_excerpt_output', 'myprefix_highlight_search' ); // Highlight excerpt terms
add_filter( 'the_title', 'myprefix_highlight_search' ); // Highlight title terms

Snippet Type: PHP

Posted Under: Search

All PHP snippets should be added via a child theme's functions.php file.