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

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

最佳答案

你只需要将下面的代码放在循环中:

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

关于php - 在 while 循环中获取当前帖子类别名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54438802/

相关文章:

css - (Wordpress CSS) 如何在 404 页面上隐藏面包屑和多余空间?

wordpress - .htaccess 重定向所有页面,除了少数页面重定向到特定页面

gmail - 如何指示gmail标签 View ?

python - 如何使用IntervalIndex生成.cat.codes

php - 对所有数组成员调用对象成员函数

php - 想要新行中的不同表行

PHP 邮件不发送但没有错误

php - 如何编写 PHP 脚本来获取给定用户在 Twitter 中的关注者数量?

php - 为什么标题小部件不显示在 Google Chrome 上?

html - 如何将自定义字段添加到 Woocommerce 中的类别?