Tom Nolan
Tom Nolan

Reputation: 1957

Display a post's category within the wordpress loop?

Okay, so I have a Wordpress template that I created that only displays posts that have the "workout" category associated with it. Within the loop that displays those, I want the categories of the specific post to be listed.

I was thinking something like this would work:

$id = get_the_ID();
$cats = wp_get_post_categories($id);

But then I do not know how to echo this out on to the screen. Anyone have any idea how I can display the categories of each post within the loop? All of the articles I have looked at have only showed how to display all categories, not display the categories associated with a specific post.

Here is the loop I have:

<div class="query">
<b><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></b>
    <?php 
        $id = get_the_ID();
        $cats = wp_get_post_categories($id);
    ?>
</div>
<?php endwhile; ?>

Upvotes: 5

Views: 38318

Answers (4)

Joseph Silber
Joseph Silber

Reputation: 219938

Get the category objects:

$cats = get_the_category($id);

Just echo the name:

echo $cats[0]->name;

If you want to output a link, use this:

<a href="<?php echo get_category_link($cats[0]->cat_ID); ?>">
    <?php echo $cats[0]->name; ?>
</a>

Note: instead of wp_get_post_categories($id), you could just use get_the_category().


Update: if you want to display all the categories, just loop through them:

<?php foreach ( $cats as $cat ): ?>

    <a href="<?php echo get_category_link($cat->cat_ID); ?>">
        <?php echo $cat->name; ?>
    </a>

<?php endforeach; ?>

Upvotes: 15

Karadjordje
Karadjordje

Reputation: 315

If anybody else needs help with this you can use this inside posts loop:

<p><?php _e( 'Category: ', 'themename' ); the_category(', '); // Separated by commas ?></p>

Upvotes: 3

Muddasir Abbas
Muddasir Abbas

Reputation: 1819

Get the post category if you have a custom post_type

<?php
$categories = get_the_terms( $post->ID, 'taxonomy' );
// now you can view your category in array:
// using var_dump( $categories );
// or you can take all with foreach:
foreach( $categories as $category ) {
    echo $category->term_id . ', ' . $category->slug . ', ' . $category->name . '<br />';
} ?>

click here for detail

Upvotes: 1

James Koussertari
James Koussertari

Reputation: 91

Thanks Joseph. I have extended your code so that the word 'Category' changes to 'Categories' when there are more than one category. There may be a better way of doing this but I couldn't find it anywhere :)

<p>
    <?php 
    $id = get_the_ID();
    $cats = get_the_category($id);
    echo ( count($cats) == 1  ? 'Category: ' : 'Categories: ');
    $c = 0; $n = 0;
    $c = count($cats);
    foreach ( $cats as $cat ):
        $n++; ?>
        <a href="<?php echo get_category_link($cat->cat_ID); ?>">
            <?php echo $cat->name; echo ( $n > 0 && $n < $c ? ', ' : ''); ?>
        </a>
    <?php endforeach; ?>
</p>

Upvotes: 3

Related Questions