Highlight Search Terms in Results
Wraps the searched words in mark tags in result titles and excerpts, so visitors see why each result matched.
Opens WPIDE on
Code
$wpide_highlight_terms = function ( $text ) {
if ( ! is_search() || ! in_the_loop() || ! is_string( $text ) ) {
return $text;
}
$terms = array_filter( preg_split( '/\s+/', trim( get_search_query( false ) ) ), function ( $term ) {
return strlen( $term ) > 1;
} );
if ( ! $terms ) {
return $text;
}
$quoted = array_map( function ( $term ) {
return preg_quote( $term, '/' );
}, $terms );
$pattern = '/(' . implode( '|', $quoted ) . ')(?![^<]*>)/iu';
$result = preg_replace( $pattern, '<mark class="search-highlight">$1</mark>', $text );
return null === $result ? $text : $result;
};
add_filter( 'the_title', $wpide_highlight_terms );
add_filter( 'the_excerpt', $wpide_highlight_terms );
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.