Highlight WordPress search terms with JQuery

Quite frankly, no one really cares about search page. I too, previously, until the day I search for a site and find it hard to catch the terms on the search page. Instead of finding it, I search using browser CTRL+F again, double my search job.

There are numorous of plugins available for WordPress to highlight the search terms, some even have tutorial on how to highlight without using a plugin. I tested, it doesn’t work too well for me. Perhaps, the updated version of JQuery conflicted with it.

Highlight

Yet again, WordPress template tags comes to save my time :) There is this the_search_query tags in WordPress. It will shows the term you searched. Simply, .replace() it with JQuery.

<script type="text/javascript" >
jQuery(document).ready(function($){
jQuery(".post").each(function() {  // The DIV of the result
  jQuery(this).html(jQuery(this).html().replace(/ <?php the_search_query(); ? >/ig, " <span class='highlight' > <?php the_search_query(); ? > </span >"));
});
}); // END
</script >

Simply placed the above code in search.php and you’re good to go :)

3 thoughts on “Highlight WordPress search terms with JQuery

  1. Hi, i use all your tips for my new twenty child theme :)
    To help some users, here is the code without whitespaces :
    [code]
    jQuery(document).ready(function($){
    jQuery(".post").each(function() { // The DIV of the result
    jQuery(this).html(jQuery(this).html().replace(/ /ig, " "));
    });
    }); // END
    [/code]
    And add to style.css
    [code].highlight {background: #dedede;}[/code] Use the color of your choice

    It’s pretty obvious but just in case … ^^

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>