Show the Matching Text in Search Results
Replaces the usual opening-lines excerpt in search results with the passage of the post that actually contains the search words.
Opens WPIDE on
Code
add_filter( 'get_the_excerpt', function ( $excerpt, $post = null ) {
if ( is_admin() || ! is_search() || ! in_the_loop() || ! $post || ! function_exists( 'mb_stripos' ) ) {
return $excerpt;
}
$terms = array_filter( preg_split( '/\s+/', trim( (string) get_search_query( false ) ) ), function ( $term ) {
return mb_strlen( $term ) > 2;
} );
if ( ! $terms ) {
return $excerpt;
}
$text = trim( preg_replace( '/\s+/u', ' ', wp_strip_all_tags( strip_shortcodes( excerpt_remove_blocks( $post->post_content ) ) ) ) );
foreach ( $terms as $term ) {
$position = mb_stripos( $text, $term );
if ( false === $position ) {
continue;
}
$start = max( 0, $position - 100 );
$passage = mb_substr( $text, $start, 260 );
if ( $start > 0 ) {
$passage = preg_replace( '/^\S*\s/u', '', $passage );
}
if ( $start + 260 < mb_strlen( $text ) ) {
$passage = preg_replace( '/\s\S*$/u', '', $passage );
}
return ( $start > 0 ? '… ' : '' ) . esc_html( $passage ) . ( $start + 260 < mb_strlen( $text ) ? ' …' : '' );
}
return $excerpt;
}, 20, 2 );
Notes
Combine it with the Highlight Search Terms snippet to mark the words inside the passage.
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.