最近对wordpress的一些小改进很感兴趣,可以让你的博客更加个性,也更有趣味性,下面的代码可以在结果中高亮你所搜索的关键词。首先把第一段代码放在functions.php中
01 function hls_set_query() {
02 $query = attribute_escape(get_search_query());
03 if(strlen($query) > 0){
04 echo '
05 <script type="text/javascript">
06 var hls_query = "'.$query.'";
07 </script>
08 ';
09 }
10 }
11 function hls_init_jquery() {
12 wp_enqueue_script('jquery');
13 }
14 add_action('init', 'hls_init_jquery');
15 add_action('wp_print_scripts', 'hls_set_query');
然后把下面的代码放在header.php中,就OK了。
01 <style type="text/css" media="screen">
02 .hls { background: #D3E18A; }
03 </style>
04 <script type="text/javascript">
05 jQuery.fn.extend({
06 highlight: function(search, insensitive, hls_class){
07 var regex = new RegExp("(<[^>]*>)|(\b"+ search.replace(/([-.*+?^${}()|[]/\])/g,"\$1") +")", insensitive ? "ig" : "g");
08 return this.html(this.html().replace(regex, function(a, b, c){
09 return (a.charAt(0) == "<") ? a : "<strong class=""+ hls_class +"">" + c + "</strong>";
10 }));
11 }
12 });
13 jQuery(document).ready(function($){
14 if(typeof(hls_query) != 'undefined'){
15 $("#post-area").highlight(hls_query, 1, "hls");
16 }
17 });
18 </script>
分类:新闻资讯