我正在循环所有帖子,并尝试输出与每个帖子相关的类别的好名称。因此,如果存在类别 A、B 和 C,且 post 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() 对于这种情况来说是理想的选择,因为你是在循环中执行此操作:
$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;
}
}
}
我在这里分享了这篇文章的详细解决方案。让我知道是否有帮助: https://wpdesc.com/advanced-wordpress/how-to-display-only-child-category-in-your-wordpress-post-loop/