【问题标题】:Wordpress - Show all child categories associated to post ID within loopWordpress - 在循环中显示与帖子 ID 关联的所有子类别
【发布时间】:2015-06-26 10:52:37
【问题描述】:

我正在遍历所有帖子,并尝试输出与每个帖子相关的类别 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; ?>

【问题讨论】:

    标签: php wordpress loops


    【解决方案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;
            }
        }
    }
    

    【讨论】:

    • 这很棒,尽管它输出父类别以及子类别。如何排除父母?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多