如何根据自定义帖子类型的子类别显示帖子?

时间:2018-11-28 06:16:12

标签: php wordpress custom-post-type custom-taxonomy

我有一个称为“类别”的自定义帖子类型,它的名称是“类别”。我有各种类别,例如:

  • 美容
    • 化妆
    • 护肤
  • 技术

我在CPT中将这些类别称为“产品”。我只想显示与子类别匹配的帖子。例如,我只想显示在自定义分类法类别中选中“彩妆”的CPT“产品”中的帖子。我尝试了以下代码:

$args= new WP_Query( array(
         'post_type' => 'Products',
         'tax_query' => array(
                        array (
                                'taxonomy' => 'categories',
                                'field' => 'slug',
                                'terms' => 'Beauty',
                            )
                        ),
           ) );
     if($args->have_posts()):
        while ($args->have_posts()):$args->the_post();
           echo get_field('name');
        endwhile; 
     endif;

但是此代码显然会显示类别被选中为“ Beauty”的帖子。它不检查子类别。谁能帮我这个忙吗?对当前代码的任何修改也将有所帮助。 谢谢!

1 个答案:

答案 0 :(得分:1)

如果要显示某个子类别的帖子,则可以简单地使用get_posts(),如下所示:

 $posts = get_posts(array(
    'post_type' => 'Products',
    'post_status'   => 'publish',
    'cat'      => your subcat ID,
    'posts_per_page'   => -1
));

然后像这样循环浏览您的帖子:

 foreach ($posts as $post){
     echo $post->post_title . '<br>';

 }
相关问题