菜鸟笔记
提升您的技术认知

wordpress 排除指定文章分类

有的时候,需要创建某个测试文章分类,比如“测试1”、“测试2”,它们的ID分别为13、14,这两个分类下的文章只供特定情况下使用,故在首页、搜索页面、分类目录等栏目都不想显示该分类下及该分类下的文章,就需要在查询的时候排除该分类及该分类下的文章。

分类目录下排除该文章分类

在functions.php中加入以下代码

function exclude_categories( $query ) {
    $query['exclude'] = '-13,-14';
    return $query;
}
add_filter( 'widget_categories_args', 'exclude_categories' );

搜索结果排除该分类的文章

在functions.php中加入以下代码

function exclude_search_category( $query) {
    if ( $query->is_search) {
        $query->set('cat','-13,-14'); 
    }
    return $query;
}
add_filter('pre_get_posts','exclude_search_category');

首页文章列表排除该分类的文章

在functions.php中加入以下代码

function exclude_category_home( $query ) {
    if ( $query->is_home ) {
        $query->set( 'cat', '-13, -14' );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );

统计文章总数排除该分类

在functions.php中加入以下代码

function exclude_category_home( $query ) {
    if ( $query->is_home ) {
        $query->set( 'cat', '-13, -14' );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );

使用wordpress内置函数调用

<?php
    $posts = get_posts( 'numberposts=-1' );
    echo count($posts);
?>

 方法二:

如果你要在首页显示的日志排除某个特定的分类,如何操作呢?下面的代码就是排除 13 和 26 这两个分类的日志。

 

<?php if ( have_posts() ) : query_posts($query_string .'&cat=-13,-26'); while ( have_posts() ) : the_post(); ?>