Home / search / Highlight search terms
  • How to Highlight search terms

    no thumbnail sorry: Highlight search terms

    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.

    ( click code to copy )

    wordpress snippet : PHP - 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');
    
    ( click code to copy )

    wordpress snippet : PHP - header.php

    <>
    <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>
    

    ( WordPress codex functions, hooks, in this snippet. )

    attribute_escape, query, init, add_action, _e, wp_enqueue_script, wp,