I must admit that I’m not a big fan of the WordPress built-in search engine. One of its weakest features is the fact that searched text aren’t highlighted in the results, so the visitor is unable to see the searched text in the context of your article.
Luckily, there’s a nice hack using regular expressions to automatically highlight searched text in search results. This code has been created by Joost de Valk who blogs at www.yoast.com.
1. Open your search.php file and find the following:
1 | echo $title; |
2. Replace with:
1 2 3 4 5 6 | <?php $title = get_the_title(); $keys= explode(" ",$s); $title = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">\0</strong>',$title); ?> |
3. Save the search.php file and open the style.css file. Append the following line to it:
1 | strong.search-excerpt { background: yellow; } |
4. You’re done. Now, the searched text will be highlighted in your search results.
How It Works:
This code is using PHP regular expressions to find the searched terms in the text returned by WordPress. When an occurrence has been found, it is wrapped in a HTML element. Then, I simply used CSS to define a yellow background to this element.
Code to Display the Most Recent Comments
There are a few plugins that will retrieve the most comments. But if you want a little more control or like to get your hands dirty in a little PHP code, there is a code snippet that will do the trick:
Posted on August 16th 2009 in Coding | No Comments »