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.