Skip to content

Snippet: 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_admin() && 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
All PHP snippets should be added via child theme's functions.php file or via a plugin. We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top