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