Highlight Search Terms Using jQuery

One way to spice up the search page is to highlight the search terms within the search results. The way described in this tutorial is using jQuery and will highlight both title and post content. Another way is not to use jQuery or using wordpress plugins which will not be describe in this tutorial.

search terms Highlight Search Terms Using jQuery

Find your theme’s functions.php file, and 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');

After that manually you can open your theme’s header.php file and paste the following code 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>

Make sure to change the “post-area” in the code to the HTML tag ID (for eg: content or post) of the area you want your search terms highlighted. You can also change the way the highlighted text styles by changing the CSS properties of the “.hls” class.

Enjoy!

 

Related Posts: