post-page

How to Highlight Search Terms with jQuery

70
responses
by
 
on
April 10th, 2009
in
HOW-TO, WordPress FAQs

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:
Highlighted Search Results

Conclusion

Few reasons why I like this method:

  1. 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.
  2. 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.
  3. 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!

heading
70
Responses

 

Comments

  1. Hicham (36 comments.) says:

    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?

    • Thaya Kareeson (51 comments.) says:

      I didn’t come across any during my search, but I’m sure there’s some out there on the net.

    • RavanH (11 comments.) says:

      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 :)

  2. Li-An (13 comments.) says:

    Very nice tip ! I try it now !

  3. Mattias (32 comments.) says:

    Nice post, things like this should be core imo.

    • Thaya Kareeson (51 comments.) says:

      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!

      • DD32 (1 comments.) says:

        Unfortunately, You’re going to have to wait for 2.9 or 3.0 before we see any major search improvements.

  4. David says:

    Nice. Be nicer still if this was a plugin so core code didn’t need modifying.

    • silent (2 comments.) says:

      it doesn’t modify core code. functions.php IS theme’s file.

  5. Danny Brown (2 comments.) says:

    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) :)

  6. PimpMyWordPress (1 comments.) says:

    Great tip!!! Can’t wait to try it on my blog

  7. Adrian says:

    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 :)

  8. George Serradinho (107 comments.) says:

    Very nice hack, must try it some day on my site. Thanks for sharing this.

  9. Loz says:

    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.

    • Thaya Kareeson (51 comments.) says:

      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.

  10. pinoy2 (1 comments.) says:

    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…

  11. Ben Licher (1 comments.) says:

    Good tip, I’ll try it and will follow the comment for the answers ont he questions above

  12. Showfom (1 comments.) says:

    Cool function!

  13. W-Shadow (3 comments.) says:

    Here it is in a plugin form and with some additional features like multiple highlight colors – Highlight Search Terms WP plugin.

    • Thaya Kareeson (51 comments.) says:

      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! :)

  14. RavanH says:

    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 :)

    • Thaya Kareeson (51 comments.) says:

      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.

      • RavanH (11 comments.) says:

        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! :)

  15. Francisco Lopez (1 comments.) says:

    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,

  16. Thomas (1 comments.) says:

    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.

    • RavanH (11 comments.) says:

      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?

  17. ZK@Web Marketing Blog (1 comments.) says:

    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.

  18. Katherine says:

    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…

  19. kaman says:

    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.

    • RavanH (11 comments.) says:

      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…

      • Thaya Kareeson (51 comments.) says:

        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.

  20. WP Tricks (5 comments.) says:

    I like it.. I want tried it on my website

  21. RavanH (11 comments.) says:

    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 ?

  22. Mike Gulline (1 comments.) says:

    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

  23. Jan Bengtsson (1 comments.) says:

    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


Tweetbacks

  1. antiprivacy (Anti-Privacy) (18 comments.) says:

    How to Highlight Search Terms with jQuery | Weblog Tools Collection http://tinyurl.com/c4xu56

  2. antiprivacy (Anti-Privacy) (18 comments.) says:

    How to Highlight Search Terms with jQuery | Weblog Tools Collection http://tinyurl.com/c4xu56

  3. antiprivacy (Anti-Privacy) (18 comments.) says:

    How to Highlight Search Terms with jQuery | Weblog Tools Collection http://tinyurl.com/c4xu56

  4. mattyc (Matthew Carlin) (1 comments.) says:

    I’m reading… How to Highlight Search Terms with jQuery | Weblog Tools Collection http://tinyurl.com/c4xu56

  5. antiprivacy (Anti-Privacy) (18 comments.) says:

    How to Highlight Search Terms with jQuery | Weblog Tools Collection http://tinyurl.com/c4xu56

  6. webupd8 (Web Upd8 Team) (5 comments.) says:

    How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1

  7. ravindra1982 (ravindra1982) (1 comments.) says:

    RT @webupd8: How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1

  8. ruhanirabin (Ruhani Rabin) (5 comments.) says:

    How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1 (RT @webupd8)

  9. giographix (Giographix Studios) (1 comments.) says:

    How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1 (RT @ruhanirabin @webupd8)

  10. chedly (Mohamed Chedly SEBAI) (1 comments.) says:

    RT @giographix: How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1 (RT @ruhanirabin @webupd8)

  11. passionsista (Vandy ) (1 comments.) says:

    RT @webupd8: How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1

  12. danosphere (Dan) (1 comments.) says:

    RT @passionsista: RT @webupd8: How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1

  13. code8 (Code8 Design+Code) (7 comments.) says:

    RT @giographix How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1 (RT @ruhanirabin @webupd8)

  14. code8 (Code8 Design+Code) (7 comments.) says:

    RT @ruhanirabin How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1 (RT @webupd8)

  15. code8 (Code8 Design+Code) (7 comments.) says:

    RT @ruhanirabin How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1 (RT @webupd8)

  16. IsaacVanName (Isaac Van Name) (4 comments.) says:

    How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1 (via @passionsista)

  17. rilwis (Tuan Anh) (1 comments.) says:

    RT @IsaacVanName: How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1 (via @passionsista)

  18. berndartmueller (Bernd Artmüller) (1 comments.) says:

    RT @rilwis RT @IsaacVanName: How to Highlight Search Terms with #jQuery http://bit.ly/HzEV1 (via @passionsista)


Trackbacks/Pingbacks

  1. [...] the full article here. Enjoyed This [...]

  2. [...] arama. This plugin is a light weight, low resource demanding and very simple fusion between How to Highlight Search Terms with jQuery – theme hack by Thaya Kareeson and Search Hilite by Ryan Boren . , Dü?ük kaynak ve nas?l jQuery ile Arama ?artlar? – tema [...]

  3. [...] Source: Thaya Kareeson on How to Highlight Search Terms with jQuery [...]

  4. [...] How to Highlight Search Terms with jQuery [...]

  5. [...] Source: weblogtoolscollection.com [...]

  6. [...] Source: How to Highlight Search Terms with jQuery [...]

  7. [...] Mijn favorieten zijn nummer 2 ( Display Thumbnails For Related Posts in WordPress ) en nummer 5 (How to Highlight Search Terms with jQuery ). Wat is jouw favoriet? Deel en bookmark [...]

  8. [...] 51. How to Highlight Search Terms With jQuery [...]

  9. [...] results. This plugin is a light weight, low resource demanding and very simple fusion between How to Highlight Search Terms with jQuery – theme hack by Thaya Kareeson and Search Hilite by Ryan Boren. This entry was posted in Uncategorized. Bookmark the permalink. [...]

  10. [...] Highlights search terms in WordPress result page. (via weblogtoolscollection) [...]

Obviously Powered by WordPress. © 2003-2013

page counter
css.php