Skip to content

Early-bird lifetime licence: $199 once, for the first 200 buyers only. See the offer

Highlight the search words in results

The words a visitor searched for are highlighted in the titles and excerpts on the search results page.

  • Type PHP
  • Runs Everywhere (runs as WordPress loads)
  • Category Search and archives
  • Tested with WordPress 7.1
PHP
<?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

Move your snippets over this afternoon.

Importing changes nothing until you switch over, and your old shortcodes keep working.