预计阅读时间: 5 分钟

将指定的页面或者某分类下的日志从搜索结果中排除

下面的函数允许您将任何分类下的日志甚至是页面从搜索结果中排除掉。

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 '
      
        var hls_query  = "'.$query.'";
      
    ';
  }
}
function hls_init_jquery() {
  wp_enqueue_script('jquery');
}
add_action('init', 'hls_init_jquery');
add_action('wp_print_scripts', 'hls_set_query'); 

再将下面这段代码放到主题的header.php文件中, 标签 的前面:


    .hls { background: #D3E18A; }


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) == "<&quot;) ? a : &quot;<strong>" + c + "</strong>";
  }));
}
});
jQuery(document).ready(function($){
if(typeof(hls_query) != 'undefined'){
  $("#post-area").highlight(hls_query, 1, "hls");
}
});

显示搜索结果条目数量

返回搜索结果数量。例如 – 对“twitter”的搜索结果数量为 – 8 篇日志。

<h2 class="pagetitle">
    Search Result for
    post_count;
    _e(''); _e('<span class="search-terms">');
echo $key; _e('</span>'); _e(' &mdash; ');
echo $count . ' '; _e('articles'); wp_reset_query();
    ?>
</h2> 
此文章对你有帮助吗? 已有 0 人说这篇文章是有用的。