Vivek
Vivek

Reputation: 33

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

Upvotes: 3

Views: 4473

Answers (3)

Manthan Kanpariya
Manthan Kanpariya

Reputation: 104

Put this inside While Loop

  global $post;
  $postcat = get_the_category( $post->ID );

Upvotes: 0

Vasim Shaikh
Vasim Shaikh

Reputation: 4512

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

Upvotes: 3

peperoli
peperoli

Reputation: 109

You can use the pre-made WordPress function the_category( $separator, $parents, $post_id ) to print the post categories as links.

Further information on the WordPress Codex: Function Reference: the_category

Edit: Print only the names:

$categories = get_the_category();

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

Upvotes: 0

Related Questions