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


Wordpress - Show all child categories associated to post ID within loop

我正在循环浏览所有帖子,并试图输出与每个帖子相关的类别nicename。因此,如果有类别A、B和C,其中X后只与类别A和C关联,那么我只想输出类别A和C的昵称。

循环如下:

<?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; ?>

听起来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;
        }
    }
}