DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

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:

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

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!

One Comment

  1. I suggest adding the extra line:

    $s = trim(ereg_replace(‘ +’, ‘ ‘, $s));

    I noticed visitors having an extra space in their search end up with bad character encoding. This will remove the extra space.

Leave a Comment

Your email address will not be published. Required fields are marked *