首页 文章

在分类存档页面上显示自定义帖子类型中的所有帖子

提问于
浏览
0

我想将我的分类档案页面重定向到帖子类型的主档案页面,显示所有帖子然后过滤它们,而不是仅显示与分类术语匹配的那些 . 我相信我需要使用pre_get_posts来改变循环,但是我不能删除分类法 . 我试过了:

if ( !is_admin() && $query->is_main_query() && $query->is_tax()) {
        $query->set( 'tax_query',array() ); 
}

if ( !is_admin() && $query->is_main_query() && $query->is_tax()) {
        $query->set( 'tax_query','' );  
}

我已经阅读了更改tax_query的解决方案,但没有删除它 .

或者,有没有更好的方法将分类档案重定向到帖子类型档案? (我搜索过这个,但一无所获 . )

1 回答

  • 0

    如果您想将分类页面重定向到它的帖子类型存档,您可以尝试类似下面的内容 .

    但是要小心!您的帖子中隐含一个假设 WP_Taxonomy 有一个 post_type 映射到它 . 实际上,您可以将分类法映射到任意多个 post_type 对象 . 下面的代码将分类法页面重定向到关联的自定义帖子类型存档,或者不是它是分类法适用的唯一一个!

    另外 - 确保你的自定义帖子类型的 has_archive 键在 register_post_type args中设置为true!

    <?php
    // functions.php
    
    function redirect_cpt_taxonomy(WP_Query $query) {
        // Get the object of the query. If it's a `WP_Taxonomy`, then you'll be able to check if it's registered to your custom post type!
        $obj = get_queried_object();
    
        if (!is_admin() // Not admin
            && true === $query->is_main_query() // Not a secondary query
            && true === $query->is_tax() // Is a taxonomy query
        ) {
            $archive_url = get_post_type_archive_link('custom_post_type_name');
    
            // If the WP_Taxonomy has multiple object_types mapped, and 'custom_post_type' is one of them:
            if (true === is_array($obj->object_type) && true === in_array($obj->object_type, ['custom_post_type_name'])) {
                wp_redirect($archive_url);
                exit;
            }
    
            // If the WP_Taxonomy has one object_type mapped, and it's 'custom_post_type'
            if (true === is_string($obj->object_type) && 'custom_post_type_name' === $obj->object_type) {
                wp_redirect($archive_url);
                exit;
            }
        }
    
        // Passthrough, if none of these conditions are met!
        return $query;
    }
    add_action('pre_get_posts', 'redirect_cpt_taxonomy');
    

相关问题