将指定的页面或者某分类下的日志从搜索结果中排除
下面的函数允许您将任何分类下的日志甚至是页面从搜索结果中排除掉。
function SearchFilter($query) {
if ($query->is_search) {
$query->set('cat','0,1');
} return $query;
}
add_filter('pre_get_posts','SearchFilter');
搜索特定的某个日志分类
这将从特定的分类中返回搜索结果:
function SearchFilter($query) {
if ($query->is_search) {
// Insert the specific categories you want to search
$query->set('cat', '8,9,12');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
搜索某一特定的日志类型
仅搜索特定的日志类型,而将其他所有类型过滤掉。
function SearchFilter($query) {
if ($query->is_search) {
// Insert the specific post type you want to search
$query->set('post_type', 'feeds');
}
return $query;
}
// This filter will jump into the loop and arrange our results before they're returned
add_filter('pre_get_posts','SearchFilter');
高亮WordPress搜索关键词(使用JQuery)
在WordPress搜索结果页面高亮显示关键词。将下面这段函数放到主题的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');
再将下面这段代码放到主题的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>
显示搜索结果条目数量
返回搜索结果数量。例如 – 对“twitter”的搜索结果数量为 – 8 篇日志。
<h2 class="pagetitle">
Search Result for
<?php /* Search Count */
$allsearch = &new WP_Query("s=$s&showposts=-1");
$key = wp_specialchars($s, 1);
$count = $allsearch->post_count;
_e(''); _e('<span class="search-terms">');
echo $key; _e('</span>'); _e(' — ');
echo $count . ' '; _e('articles'); wp_reset_query();
?>
</h2>