This is the OLD WebbyZone archive. Click Here if you wish to check out the all NEW WebbyZone.
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>
8:44 am
yeah, this is very helpful. Thank you