Highlight search terms

Wpsnipp – In an attempt to make your WordPress search even more user friendly, you can highlight the search terms in the results. We did this for one of our clients, so we thought it would be useful for other users. In this article we will show you how you can highlight search terms in the results in WordPress.

Adding the first block of PHP code to your wordpress functions.php file. Then add the second block of code to the header.php file of your wordpress theme.



function hls_set_query() {
$query  = attribute_escape(get_search_query());
if(strlen($query) > 0){
echo '
<script type="text/javascript">
var hls_query  = "'.$query.'";
function hls_init_jquery() {
add_action('init', 'hls_init_jquery');
add_action('wp_print_scripts', 'hls_set_query');

<style type="text/css" media="screen">
.hls { background: #D3E18A; }
<script type="text/javascript">
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=""+ hls_class +"">" + c + "</strong>";
if(typeof(hls_query) != 'undefined'){
$("#post-area").highlight(hls_query, 1, "hls");

Leave a comment