This is the OLD WebbyZone archive. Click Here if you wish to check out the all NEW WebbyZone.

Highlight Search Terms in WordPress with jQuery

Post image of Highlight Search Terms in WordPress with jQuery
Filed in Web Development 1 comments

Highlighting search terms in content is a great way of displaying the relevancy of the page to its viewers. In Wordpress, this can be achieved with the help of a simple tweak. Both title and post contents can be highlighted using the following code snippet.

In the WordPress theme’s function.php file, paste the following code:

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');

Open the theme’s header.php and paste the following code (just before the </head> tag):

<style type="text/css" media="screen">
  .hls { background: #D3E18A; } /* <- Change the CSS style of */
                                /*    highlighted texts here. */
</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=\""  hsl_class  "\">"   c   "</strong>";
    }));
  }
});
jQuery(document).ready(function($){
  if(typeof(hls_query) != 'undefined'){
    $("#post-area").highlight(hls_query, 1, "hls"); // <- Change 'post-area' to ID of HTML tag you
                                                    //    want to highlight search terms in.
  }
});
</script>
Posted by Ranadeep   @   24 September 2009 1 comments
Tags : , , , ,

1 Comments

Comments
Mar 5, 2010
8:44 am
#1 ez :

yeah, this is very helpful. Thank you

Leave a Comment

Name

Email

Website

Previous Post
«
Next Post
»
CrossBlock designed by ZenVerse