在while循环中获取当前帖子类别名称

时间:2019-01-30 10:50:19

标签: php wordpress categories posts

我创建了一个自定义帖子类型“ stm_media_gallery” 在此自定义帖子类型中还有三个类别。 我想显示与每个帖子相关的类别名称。

<?php $gallery_query = new WP_Query( array('post_type' => 
'stm_media_gallery', 'posts_per_page' => -1) );
 if( $gallery_query->have_posts() ) : 
 while( $gallery_query->have_posts() ) : $gallery_query->the_post(); ?>
      --Display post name and its category name
 <?php endif; ?>
 <?php endwhile; ?>

3 个答案:

答案 0 :(得分:0)

您只需要将以下代码放入循环中:

<div>
<?php 
    foreach((get_the_category()) as $category){
        echo $category->name."<br>";
        echo category_description($category);
        }
    ?>
</div>

更新现有代码

    <?php $gallery_query = new WP_Query( 
      array('post_type' => 'stm_media_gallery',
       'posts_per_page' => -1) );

 if( $gallery_query->have_posts() ) : 
 while( $gallery_query->have_posts() ) : $gallery_query->the_post(); 

    $gallery_category = get_the_category( get_the_ID() );

    the_title( '<h3>', '</h3>' ); 
    echo "<br>";
  <?php foreach ( $gallery_category as $key => $value) { echo $value->category_nicename; } ?>


 <?php endif; ?>
 <?php endwhile; ?>

答案 1 :(得分:0)

您可以使用预制的WordPress功能the_category( $separator, $parents, $post_id )将帖子类别打印为链接。

有关WordPress Codex的更多信息:Function Reference: the_category

编辑:仅打印名称:

$categories = get_the_category();

if ( ! empty( $categories ) ) {
    echo esc_html( $categories->name );   
}

答案 2 :(得分:0)

将此内容放入While循环

  global $post;
  $postcat = get_the_category( $post->ID );
相关问题