【问题标题】:WP custom post type query does not return custom taxonomyWP 自定义帖子类型查询不返回自定义分类
【发布时间】:2019-06-04 13:32:57
【问题描述】:

我有以下 CPT:

        array(
            'slug'        => 'articles',
            'single_name' => 'Article',
            'plural_name' => 'Articles',
            'menu_name'   => 'Articles',
            'description' => '',
            'dashicon'    => 'dashicons-media-default'
        ),

以及出现在文章 CPT 下的以下自定义分类法:

        array(
            'slug'        => 'author',
            'single_name' => 'Author',
            'plural_name' => 'Authors',
            'menu_name'   => '→ Authors',
            // This is where you sync the taxonomy to the post types above
            'post_type'   => ['articles', 'news']
        ),

现在,我正在尝试创建一个 single-articles.php,我在其中查询一篇文章,以包含所有自定义分类信息。

我尝试了以下所有变体:

$args = array(
    'post_type' => 'articles',
    'tax_query' => array(
        array(
            'taxonomy' => 'author',
            'field' => 'slug'
        ),
    ),
);

我对 PHP 和 WP 比较陌生,并且不能 100% 确定如何检索数据。在 Javascript 中,你会得到一个可以遍历的对象。添加print_r($my_query) 时,我没有得到我想要的东西。在文档的前面,我已经启动了循环:

if (have_posts()) :
  while (have_posts()) : the_post()

但我不明白为什么 php/wp 不显示对象中包含的所有数据。理想情况下,我只想查询单篇文章并取回所有数据,以包含有关所有附加分类的信息。我想按分类查询文章所以我有两个问题:

1) 如何正确查询以获取结果? 2) 我如何在前端显示这些数据?

编辑:According to this tax_queryis_singular() 为真时被忽略。 print_r( is_singular() ) 结果为 1(又名是真的?!),这会有什么不同吗?

我还为分类法附加了自定义帖子类型。我也需要检索此信息。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    你的分类标签是author而不是authors

    $args = array(
    'post_type' => 'articles',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'author',
            'field' => 'slug',
            'terms' => 'your-term-here',
        ),
      ),
    );
    

    您可以使用 single-{posttype}.php 作为单个模板。

    而且,如果您已将 has_archive 参数设置为 true 来注册您的帖子类型,那么您可以使用 archive-{posttype}.php 作为您的存档模板。

    您可以查看Template Hierarchy

    【讨论】:

    • 抱歉,我编辑了帖子以更正问题。你能告诉我如何在前端检索信息,因为这个查询可以工作吗?
    • 查看我最近的编辑...您需要通过'terms' => 'your-term', 来获取特定术语的所有文章
    猜你喜欢
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2018-09-22
    • 2017-04-18
    • 1970-01-01
    相关资源
    最近更新 更多