How to Highlight Search Terms with jQuery
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.
Paste the following code in 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');
After that you need to open your theme’s header.php 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 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.





Comment by Nick — August 20, 2010 @ 8:58 pm
hi nice article… but your .css is not correct.
Your singleposts does not look very good near the share box at top… the code box is overlapping the box which makes it look pretty wrong in firefox etc.
Fix it by adding “overflow:hidden;” to you class .syntaxhighlighter