Skip to content

Highlighting search terms in WordPress search results

Warning: this article was written over 10 years ago, some information may be out of date.

Here is a small but helpful trick reported by Yoast for highlighting search terms in search results: in your template, modify the search.php file by replacing the_title(); with echo $title;.
On the line just above, add the following code:

$title = get_the_title();
$keys  = array_map( 'preg_quote', explode( " ", get_query_var('s') ) );
$title = preg_replace( '/(' . implode( '|', $keys ) . ')/iu',
'<strong class="search-excerpt">�</strong>', $title );

Then edit the style.css file by adding the following:

strong.search-excerpt {background: yellow;}

And that’s it.

Previous article

Next article

Thread

Leave a comment

Your email address will not be published.