A neat way to spice up your WordPress search page is to highlight search terms within your search results. I’ve seen some tutorials on the net on how to do this, but I haven’t found one that highlights both title and post content and is a drop-in modification for WordPress. Today I will bring you this drop-in hack for highlighting search terms on your WordPress blog.
1. Copy and paste the following code into your theme’s functions.php file:
If you are having issues with copy-paste from this blog, here is a link to the same code in a txt file: Code to insert into functions.php
2. Copy and paste the following code into your theme’s header.php file (just before the </head> tag is fine):
If you are having issues with copy-paste from this blog, here is a link to the same code in a txt file: Code to insert into header.php
3. Very Important: Next make sure you change “post-area” in the code (in step 2) to the HTML tag ID of the area you want your search terms highlighted. For example, if you do a view source on Weblog Tools Collection’s search result page, you will see that the results area is enclosed by the tag ‘<div id=”post-area”>’.
4. Optional: You can also change the way the highlighted text look by changing the CSS properties of the “.hls” class in the code in step 2.
Few reasons why I like this method:
- jQuery will let you highlight any text within any HTML element you desire. It doesn’t matter if the text is in the title or is in the actual post content. Just change the ID tag as needed.
- There is no need for a plugin to do some simple search term highlighting. This method should take you less than 15 minutes to hack into your theme and it makes your WordPress search page look MUCH better.
- It is highly customizable (provided that you read some jQuery documentation) to fit any blog’s needs.
Do you have a better way of doing this? If so, please share in comments!