在分类存档页面上以自定义 post 类型显示所有 post

Show all posts in a custom post type on a taxonomy archive page

我想将我的分类存档页面重定向到 post 类型的主存档页面,显示所有 post,然后过滤它们,而不是只显示与分类匹配的那些学期。我相信我需要使用 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 的解决方案,但没有将其删除。

或者,是否有更好的方法将分类档案重定向到 post 类型的档案? (我已经搜索过了,但一无所获。)

如果你想将分类法页面重定向到它的 post 类型的存档,你可以尝试下面的方法。

不过要小心!您的 post 中隐含了一个假设,即 WP_Taxonomy 有一个 post_type 映射到它。实际上,您可以将分类法映射到任意数量的 post_type 对象。下面的代码将分类法页面重定向到关联的自定义 post 类型存档,无论它是否是唯一适用于分类法的!

此外 – 确保您的自定义 post 类型在其 register_post_type args 中将 has_archive 键设置为 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');