wordpress 排除指定文章分类

WP教程评论8281字数 936阅读模式

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

wordpress 排除指定文章分类

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

在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);
?>

本文已通过「原本」原创作品认证,转载请注明文章出处及链接。

夏日阳光
  • 本文由 夏日阳光 发表于 2019年2月26日
  • 本文为夏日阳光原创文章,转载请务必保留本文链接:https://www.pieruo.com/38.html
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证