A neat way to spice up your WordPress search page is to highlight search terms within your search results. I’ve seen some tutorials on the net on how to do this, but I haven’t found one that highlights both title and post content and is a drop-in modification for WordPress. Here is the complete tutorial for highlighting search terms on your WordPress blog.

Copy and paste the following code into your theme’s functions.php file:

function hst_set_query() {

$query = attribute_escape(get_search_query());

if($query != “”){

echo ‘‘;

}

}

function hst_init_jquery() {

wp_enqueue_script(‘jquery’);

}

add_action(‘init’, ‘hst_init_jquery’);

add_action(‘wp_print_scripts’, ‘hst_set_query’);

Copy and paste the following code into your theme’s header.php file just before the ending head element:

<style type=”text/css” media=”screen”>.hst { background: #D3E18A; }</style>

<script type=”text/javascript”>

jQuery.fn.extend({

highlight: function(search, insensitive, hst_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=\””+ hst_class +”\”>” + c + “</strong>”;

}));

}

});

jQuery(document).ready(function($){

if(typeof(hst_query) != ‘undefined’){

$(“#post-area”).highlight(hst_query, 1, “hst”);

}

});

</script>

Note: Make sure you change “post-area” in the to the HTML tag ID of the area you want your search terms highlighted.

LEAVE A REPLY

Please enter your comment!
Please enter your name here