How to Highlight Search Terms with jQuery
SHARE THIS

A neat way to spice up your WordPress search page is to highlight search terms within your search results. The solution described in this tutorial will highlight both the title and post content and is a drop-in modification for WordPress.

2-Week 30-40% OFF Promo

Paste the following code in your theme’s functions.php file.

[php]
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’);
[/php]

After that you need to open your theme’s header.php and paste the following code before the < /head > tag.

[php]
<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>
[/php]

Make sure you change “post-area” in the code to the HTML tag ID of the area you want your search terms highlighted. You can also change the way the highlighted text look by changing the CSS properties of the “.hls” class.

19,612 Website Templates and Themes From $3