pasckr 发表于 2016-5-12 18:19:11

WordPress博客高亮显示搜索关键词






                最近对wordpress的一些小改进很感兴趣,可以让你的博客更加个性,也更有趣味性,下面的代码可以在结果中高亮你所搜索的关键词。首先把第一段代码放在functions.php中:
function hls_set_query() {$query= attribute_escape(get_search_query());if(strlen($query) > 0){    echo '      <script type=&quot;text/javascript&quot;>      var hls_query= &quot;'.$query.'&quot;;      </script>    ';}}function hls_init_jquery() { wp_enqueue_script('jquery');}add_action('init', 'hls_init_jquery');add_action('wp_print_scripts', 'hls_set_query');  然后把下面的代码放在header.php中,就OK了。
<style type=&quot;text/css&quot; media=&quot;screen&quot;>    .hls { background: #D3E18A; }</style><script type=&quot;text/javascript&quot;>   jQuery.fn.extend({   highlight: function(search, insensitive, hls_class){       var regex = new RegExp(&quot;(<[^>]*>)|(b&quot;+ search.replace(/([-.*+?^${}()|[]/])/g,&quot;$1&quot;) +&quot;)&quot;, insensitive ? &quot;ig&quot; : &quot;g&quot;);       return this.html(this.html().replace(regex, function(a, b, c){         return (a.charAt(0) == &quot;<&quot;) ? a : &quot;<strong class=&quot;&quot;+ hls_class +&quot;&quot;>&quot; + c + &quot;</strong>&quot;;      }));   }   });   jQuery(document).ready(function($){    if(typeof(hls_query) != 'undefined'){      $(&quot;#post-area&quot;).highlight(hls_query, 1, &quot;hls&quot;);   }});</script>
页: [1]
查看完整版本: WordPress博客高亮显示搜索关键词