Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current post category name inside while loop

I created a custom post type "stm_media_gallery" And three category inside this custom post type. I want to display category name associated with each post.

<?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; ?>
like image 325
Vivek Avatar asked Feb 28 '26 00:02

Vivek


1 Answers

You just need to put following code inside loop :

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

Update in existing code

    <?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; ?>
like image 77
Vasim Shaikh Avatar answered Mar 01 '26 13:03

Vasim Shaikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!