How to: enlight searched text in search results

January 10, 2009 at 8:58 am

Many WordPress users find the search function a bit imcomplete. For exemple, it don’t automatically hightlight the searched text. In this recipe, I’m going to show you how to do it with help from regular expressions.

Open your search.php file and find the the_title() function. Replace it with the following:

echo $title;

Now, just before the modified line, add this code:

<?php
	$title 	= get_the_title();
	$keys= explode(" ",$s);
	$title 	= preg_replace('/('.implode('|', $keys) .')/iu',
		'<strong class="search-excerpt">\0</strong>',
		$title);
?>

Save the search.php file and open style.css. Append the following line to it:

strong.search-excerpt { background: yellow; }

That’s all. Better, isn’t it?

Credits goes to Joost de Valk for this awesome recipe!