七色太阳花 發表於 2023-9-13 00:00:00

wordpress博客搜索关键词高亮显示实现代码

<p>
<span style='font-family: tahoma, arial, "Microsoft YaHei"; font-size: 14px;'>最近对wordpress的一些小改进很感兴趣,可以让你的博客更加个性,也更有趣味性,下面的代码可以在结果中高亮你所搜索的关键词。首先把第一段代码放在functions.php中: </span></p>
<div style='margin: 3px auto 0px; padding: 0px 3px; outline: none; line-height: 21.6px; clear: both; border-width: 1px; border-style: solid; border-color: rgb(0, 153, 204); background: rgb(246, 251, 255); overflow: hidden; font-family: tahoma, arial, "Microsoft YaHei";'>
<p style="margin: 0px; padding: 0px; outline: none; float: right; line-height: 25.2px; font-size: 14px;">
<span style="line-height: 25.2px; cursor: pointer;"><u>复制代码</u></span></p>
<p>
代码如下:</p>
</div>
<p style='margin: 0px auto 3px; padding: 0px 3px; outline: none; line-height: 25.2px; font-size: 14px; clear: both; border-right: 1px solid rgb(0, 153, 204); background: rgb(221, 237, 251); overflow: hidden; border-left: 1px solid rgb(0, 153, 204); word-break: break-all; border-bottom: 1px solid rgb(0, 153, 204); word-wrap: break-word; font-family: tahoma, arial, "Microsoft YaHei";'>
<br>
function hls_set_query() { <br>
$query = attribute_escape(get_search_query()); <br>
if(strlen($query) &gt; 0){ <br>
echo ' <br>
&lt;script type="text/javascript"&gt; <br>
var hls_query = "'.$query.'"; <br>
&lt;/script&gt; <br>
'; <br>
} <br>
} <br>
function hls_init_jquery() { <br>
wp_enqueue_script('jquery'); <br>
} <br>
add_action('init', 'hls_init_jquery'); <br>
add_action('wp_print_scripts', 'hls_set_query');  然后把下面的代码放在header.php中,就OK了。 <br>
&lt;style type="text/css" media="screen"&gt; <br>
.hls { background: #D3E18A; } <br>
&lt;/style&gt; <br>
&lt;script type="text/javascript"&gt; <br>
jQuery.fn.extend({ <br>
highlight: function(search, insensitive, hls_class){ <br>
var regex = new RegExp("(&lt;[^&gt;]*&gt;)|(b"+ search.replace(/([-.*+?^${}()|[]/])/g,"$1") +")", insensitive ? "ig" : "g"); <br>
return this.html(this.html().replace(regex, function(a, b, c){ <br>
return (a.charAt(0) == "&lt;") ? a : "&lt;strong+ hls_class +""&gt;" + c + "&lt;/strong&gt;"; <br>
})); <br>
} <br>
}); <br>
jQuery(document).ready(function($){ <br>
if(typeof(hls_query) != 'undefined'){ <br>
$("#post-area").highlight(hls_query, 1, "hls"); <br>
} <br>
}); <br>
&lt;/script&gt; </p>
頁: [1]
查看完整版本: wordpress博客搜索关键词高亮显示实现代码