Post Pic

How to: enlight searched text in search results

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!

One Response

Dec 01 2011 23:06

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.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox