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.
Installation
1. Copy and paste the following code into your theme’s functions.php file:
function hls_set_query() { $query = attribute_escape(get_search_query()); if(strlen($query) > 0){ echo ' <script type="text/javascript"> var hls_query = "'.$query.'"; </script> '; } } function hls_init_jquery() { wp_enqueue_script('jquery'); } add_action('init', 'hls_init_jquery'); add_action('wp_print_scripts', 'hls_set_query');
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):
<style type="text/css" media="screen"> .hls { background: #D3E18A; } </style> <script type="text/javascript"> jQuery.fn.extend({ highlight: function(search, insensitive, hls_class){ var regex = new RegExp("(<[^>]*>)|(\\b"+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +")", insensitive ? "ig" : "g"); return this.html(this.html().replace(regex, function(a, b, c){ return (a.charAt(0) == "<") ? a : "<strong class=\""+ hls_class +"\">" + c + "</strong>"; })); } }); jQuery(document).ready(function($){ if(typeof(hls_query) != 'undefined'){ $("#post-area").highlight(hls_query, 1, "hls"); } }); </script>
(jQuery code slightly adapted from devthought’s JavaScript RegExp based highlighting.)
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.
End Result
I’ve searched for “greet” on my blog and this is what shows up on the result page:
Conclusion
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!
This is very neat!
I wonder whether there’s another code that highlights the results in two colours in case I searched for 2 words?
I didn’t come across any during my search, but I’m sure there’s some out there on the net.
Thanks Thaya for your reply 🙂
I did a little WordPress plugin based on this article (I am not the only one I saw 😉 ) where similar to this code does wrapping for an array of search terms:
[code]
jQuery(document).ready(function($){
if(typeof(hls_query) != ‘undefined’){
for (i in hls_query){
$(‘#post-area’).highlight(hls_query[i], 1, ‘hilite term-‘ + i);
}
}
});
[/code]
The plugin is suitebly called Highlight Search Terms and you can find it in WP Extend 🙂
Very nice tip ! I try it now !
Nice post, things like this should be core imo.
I think the Automattic team is aware that search has been pretty lacking in WordPress, and they are working hard to make the default search a lot better. Let’s see what they come up with in version 2.8!
Unfortunately, You’re going to have to wait for 2.9 or 3.0 before we see any major search improvements.
Nice. Be nicer still if this was a plugin so core code didn’t need modifying.
it doesn’t modify core code. functions.php IS theme’s file.
You could also use the Lijit search plugin. This brings back results from not only your blog, but your network and contacts as well as the general web.
It also offers search results and analytics behind the scenes. Seriously, awesome little plugin.
You can see it in action on my blog:
http://dannybrown.me/
Or just go straight to Lijit and set up your details:
http://www.lijit.com/
(And no, this is *not* a sponsored comment) 🙂
Great tip!!! Can’t wait to try it on my blog
Yeah, it’s great, useful and easy to add on the theme.
But i have a problem with it:
I’m only getting the first post of each search highlighted, any idea?
Thank you and good job 🙂
Ok I’ve fixed it, wrong ID.
Very nice hack, must try it some day on my site. Thanks for sharing this.
Hi
thanks for the tip.
However I have found a problem.
It works just fine for single phrase words. But 2 phrase words the page just keeps refreshing itself.
It works fine for me for 2+ search phrases. There might be some other JavaScript on your page that is causing your page to reload. I’m guessing that there is some sort of JavaScript has an action bounded to a HTML element (could be anything from <a> links to <div> blocks) that might be causing the page to reload if the HTML element is modified in anyway.
If this method doesn’t work for you, you might want to try one of the more established WordPress plugins, such as Search Unleashed. Though the plugin has a heavier footprint than this hack, it might work well for you.
very nice post.. i just see some blogs with highlighted wordpress post if you land in their wp blog.
If you search in search engines and some highlighted words are comming from the top screen saying
“are you looking for these terms: _ _ _”
Then highlight all the the search terms…
This mightbe the big help i need…
Good tip, I’ll try it and will follow the comment for the answers ont he questions above
Cool function!
Here it is in a plugin form and with some additional features like multiple highlight colors – Highlight Search Terms WP plugin.
Thanks W-Shadow. I would’ve created a plugin out of it myself, but I have too many things on my hands right now to support another plugin! 🙂
Two things i wonder:
1. Doesn’t the script use the reserved ‘syntax’ class incorrectly? `highlight: function(search, insensitive, class)` should be something like `highlight: function(search, insensitive, hls_class)`
2. How would i go about it if I wanted to subject EVERYTHING inside the to the script, not just what’s inside some div with some ID? `$(“body”).highlight(hls_query, 1, “hls”);` seems to generate problems for FireFox but works in IE…
Thanks for any thoughts on this 🙂
You are right, it should be hls_class to not violate the reserved word. I will change the post. Thank you!
Everything inside a tag? The syntax you gave me shouldn’t been fine according to the jQuery documentation.
I thought so too but found that when using $(”body”) I got very weird results in FF2 and FF3.
It seems to be some kind of conflict with about EVERY other little piece of javascript on the same page… a small date script, google analytics script, skype check script, google ads, and many others. After disabling about every other script, the highlights worked in FF.
Strange how this apparently is no issue at all when any div ID or even class is used…
Anyway, thanks for this article and response! 🙂
Take out the \\b off the var regex variable, if you want to match the term any where in the text – not just at a word boundary.
var regex = new RegExp(“(]*>)|(“+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,”\\$1″) +”)”, insensitive ? “ig” : “g”);
Cheers,
Thanks, Fransisco, for this tip. I’ll be testing with it 🙂
Tried to make this work, but keep running into an issue caused by a conflict with my theme, which uses the DIV ID Container. RavanH’s plugin caused the same issue. Ah well.
Hi Thomas, at first I had set up my plugin to use “body” as post-area so that a user could then use custom CSS to control to which area highlighting would be limited. While this approach should work (as far as I can figure) this turned out to result in some unpredictable behaviour in different browsers and to conflict with about EVERY other bit of javascript on the same page. So I decided to hard code the container ID #content which is used in a wide variety of themes. Do I understand correctly that you changed the code of the plugin to use #container and still there is a conflict? If so, can you give me a link or contact me directly (see plugin) so I can take a look at what might be happening?
As you may have noticed if you read this blog on occasion I’ve been doing quite a bit of work with the jQuery JavaScript library in the last few months. I’ve kind of fallen into a couple of very client heavy projects and jQuery is turning out to be a key part in these particular projects. jQuery is definitely one of those tools that has got me really excited as it has changed my perspective in Web Development considerably from dreading of doing client development to actually looking forward to applying richer and more interactive client principles.
It’s great feature, but it doesn’t work…
I insert necessary code, change #content to .post, but there is no any highlighting (even if I enable Default theme).
What’s the problem?
WordPress 2.8.6 + plugins:
Google Analytics,
Akismet,
All in one SEO,
Contact Form 8,
Shutter Reloaded and Subscribe to Comments…
Help please!
I did everything according to your instruction.
And it works…
BUT, when I add google adsense code in the index.php(I think the wordpress search results page use index.php too)…..it does NOT work any more. I only can see a blank page.
Remove either google adsense code or your JS code…the results will be OK.
Why? thanks very much.
I noticed the same. And with lots of other javascript too. After making this high-lite code into a wordpress plugin I ran into toooo much problems by various users that I have long abandoned the project 🙁 too bad…
That’s a bummer! I’m only guessing, but this might be because the regex is searching and replacing stuff in other JavaScripts. I’m not sure if there’s a way to fix this other than just making sure that all JavaScripts do not clash with this on your search page.
I like it.. I want tried it on my website
Ran into an error in IE8: Object doesn’t support this property or method
And the error line: var regex = new RegExp(‘(]*>)|(\\b’+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,’\\$1′) +’)’, insensitive ? ‘ig’ : ‘g’);
Anyone know what’s wrong with the regular expression in IE ?
just what i was looking for… almost!
i tweaked your js a bit to highlight multiple word matches (each with their own, incremental class!). i am sure it will be of use to someone (ME).
if(typeof(hls_query) != ‘undefined’){
hls_queryA = hls_query.split(‘ ‘);
for(var i=0; i<hls_queryA.length; i++) {
$("#post-area").highlight(hls_queryA[i], 1, "hls"+i);
}
}
as you can see, i just split your "hls_query" into an array and looped through, incrementing the "hls" class along the way.
be sure to add the new styles to your CSS…
hls0 {color}
hls1 {color}
hls2 {color}
hls3 {color}
and so on…
thanks again! great script.
mike
Hi, I’m using this nice script on two Swedish sites. It works very well – with one exception: When the search term has one of the Swedish special characters åäöÅÄÖ as the initial letter, the script fails to find the word on the page. I suppose this issue can be handled by the regular expression, but I don’t know how. Anyone able to help? Thank’s in advance. //Jan