首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何从Archive.php WordPress中排除类别

从Archive.php WordPress中排除类别的方法有多种。以下是其中一种常用的方法:

  1. 使用pre_get_posts钩子函数:在functions.php文件中添加以下代码:
代码语言:txt
复制
function exclude_category_archive( $query ) {
    if ( $query->is_category() && $query->is_main_query() ) {
        $query->set( 'cat', '-1,-2,-3' ); // 将1、2、3替换为要排除的类别ID
    }
}
add_action( 'pre_get_posts', 'exclude_category_archive' );

上述代码中,我们使用了pre_get_posts钩子函数来修改查询参数。首先,我们检查当前查询是否为类别页面(is_category()),并且是主查询(is_main_query())。然后,使用set()方法将要排除的类别ID传递给查询参数('cat')。在上述代码中,我们将1、2、3替换为要排除的类别ID。如果要排除多个类别,可以使用逗号分隔。

  1. 使用pre_get_posts钩子函数和get_query_var()函数:在functions.php文件中添加以下代码:
代码语言:txt
复制
function exclude_category_archive( $query ) {
    if ( $query->is_category() && $query->is_main_query() ) {
        $excluded_categories = array( 1, 2, 3 ); // 将1、2、3替换为要排除的类别ID
        $current_category = get_query_var( 'cat' );
        
        if ( ! empty( $current_category ) ) {
            $current_category_array = explode( ',', $current_category );
            $excluded_categories = array_merge( $excluded_categories, $current_category_array );
        }
        
        $query->set( 'category__not_in', $excluded_categories );
    }
}
add_action( 'pre_get_posts', 'exclude_category_archive' );

上述代码中,我们首先定义了要排除的类别ID数组($excluded_categories)。然后,使用get_query_var()函数获取当前类别页面的类别ID($current_category)。如果当前类别ID不为空,我们将其转换为数组,并与要排除的类别ID数组合并。最后,使用set()方法将排除的类别ID传递给查询参数('category__not_in')。

无论使用哪种方法,都需要将代码添加到主题的functions.php文件中。请确保在修改代码之前备份文件,以防止意外错误。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券