【问题标题】:Show all posts in a custom post type on a taxonomy archive page在分类存档页面上以自定义帖子类型显示所有帖子
【发布时间】:2018-08-29 22:51:15
【问题描述】:

我想将我的分类存档页面重定向到帖子类型的主存档页面,显示所有帖子然后过滤它们,而不是只显示与分类术语匹配的帖子。我相信我需要使用 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) 重定向用户(发送 301 响应),或 2) 更改分类 URL 的内容以查看喜欢主存档页面?我认为 #1 更可取!
  • 老实说什么都行!我也试图重定向,但仍然只是为了分类而通过循环。

标签: php wordpress archive taxonomy


【解决方案1】:

如果您想将分类页面重定向到它的帖子类型存档,您可以尝试以下操作。

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

另外 - 确保您的自定义帖子类型在它的 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');

【讨论】:

  • 谢谢,这行得通。感谢您的警告,我确实有一个用于不止一种帖子类型的分类法。
  • 您知道为什么,当我将分类法添加为查询字符串(例如 '?theme=nature')时,它会导致重定向中出现循环吗?
  • 我最好的猜测是它以某种方式保留了查询字符串。在重定向之前执行var_dump($archive_url);die; 的输出是什么?
  • 好的,我看到了这个问题。 WP 将我的查询字符串解释为对分类页面的调用,因此它陷入了循环。如果我将“主题”更改为“主题”,它工作正常。所以最好这样做,然后从我的 GET 结果中删除“x”。
  • 对您对多个帖子类型非常有用的选项的评论 - object_type 没有出现在 get_queried_object 中,因为它是分类对象而不是帖子类型对象。
猜你喜欢
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
相关资源
最近更新 更多