Highlight the search words in results
The words a visitor searched for are highlighted in the titles and excerpts on the search results page.
<?php
$snipfire_highlight = static function ( $text ) {
if ( is_admin() || ! is_search() || ! in_the_loop() ) {
return $text;
}
$words = array_filter( array_map( 'trim', explode( ' ', (string) get_search_query( false ) ) ), static fn( $w ) => mb_strlen( $w ) > 1 );
if ( ! $words ) {
return $text;
}
$pattern = '/(' . implode( '|', array_map( static fn( $w ) => preg_quote( $w, '/' ), $words ) ) . ')(?![^<]*>)/iu';
return (string) preg_replace( $pattern, '<mark class="search-highlight">$1</mark>', $text );
};
add_filter( 'the_title', $snipfire_highlight );
add_filter( 'get_the_excerpt', $snipfire_highlight, 20 );
In these packs
- Search and archives: Better site search and cleaner archive pages.