Wordpress - 显示与循环内的帖子ID关联的所有子类别

时间:2015-06-26 10:52:37

标签: php wordpress loops

我正在浏览所有帖子,我正在尝试输出与每个帖子相关的类别nicename。因此,如果类别A,B和C的帖子X只与A类和C类相关联,那么我只想输出A类和C类的nicename。

这是循环:

<?php $subs = new WP_Query( array( 'post_type' => 'case-study' ));
  if( $subs->have_posts() ) : while( $subs->have_posts() ) : $subs->the_post(); ?>

  <?php the_title(); ?>

  <p>Associated Child Categories</p>
  //Show nicenames of each child category associated to each post
  <?php $category = get_categories($post->ID);
        foreach(($category) as $cats) { echo $category->category_nicename; }?>

<?php endwhile; endif; ?>

1 个答案:

答案 0 :(得分:1)

听起来get_the_category()对于这种情况来说是理想的,因为你在The Loop中这样做:

$post_cats = get_the_category();
if ( $post_cats ) {
    foreach ( $post_cats as $cat ) {
        // Only show child categories (exclude parents)
        if ( ! $cat->category_parent === '0' ) {
            echo $cat->cat_name;
        }
    }
}