Highlight the Searched Text!

Some themes have a highlighted search page, some themes don’t have this page too. But i will give some code to you. With this code you can highlight the searched text on your theme. This function may help your users when they search any important things. Lets Begin..

We will change our theme’s function.php and header.php. If you don’t know about WordPress coding or PHP please don’t touch this files. If you wanna help send me e-mail about this function.

Here is the code;

First make a backup functions.php and header.php (These files under the your themes path [wp-content/theme/your-theme]). After backup, you can change this files and you can send them to your server.

Insert this code into theme’s Functions.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');

And after that, Open your theme’s header.php and paste this code before </head> tag.

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

After that you can send files to your server. When you search you can see searched texts are highlighted!


Related posts:

If you enjoyed this post, make sure you subscribe to my RSS Feed
Comments are closed.
Highslide for Wordpress Plugin