Geoff
Geoff

Reputation: 317

in Wordpress display all categories for post in loop

I'm looking for a better way to output a list of categories for a post in the loop. This is what I have:

<?php $category = get_the_category(); ?>
<a href="<?php echo get_category_link($category[0]->cat_ID); ?>"><?php echo $category[0]->cat_name; ?></a>, 
<a href="<?php echo get_category_link($category[0]->cat_ID); ?>"><?php echo $category[1]->cat_name;?></a>, 
<a href="<?php echo get_category_link($category[0]->cat_ID); ?>"><?php echo $category[2]->cat_name;?></a>

Obviously thats not great because if there's not three categories I'll get redundant commas. What is the best way to loop through and output categories, with commas in between?

Thanks very much

Upvotes: 0

Views: 1356

Answers (2)

andreivictor
andreivictor

Reputation: 8511

This code should work:

<?php
$separator = ',';
$output = '';
$categories = get_the_category();
if ($categories){

    foreach($categories as $category) {
        $output .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
    }

echo trim($output, $separator);
}
?>

More info and examples about get_the_category() function on wordpress codex

Upvotes: 1

zoranc
zoranc

Reputation: 2456

you can use

<?php echo get_the_category_list(); ?>

which will output everything in this format(as a list):

<ul class="post-categories">
    <li>
        <a href="http:myblog.com/category/business" title="View all posts in Business" rel="category tag">Business</a>
    </li>
</ul>

you can read more about that here

or alternatively if you use

 <?php wp_get_post_categories( $post_id, $args ); ?> 

it will output the category ids as an array

so something like

$post_categories = wp_get_post_categories( $post->ID );
foreach($post_categories as $c){
    $cat = get_category( $c );
    $link = get_category_link( $c );
    echo "<a href='{$link}'>{$cat->name}</a>";
}

might work for you better

you can read more about this function here

Upvotes: 1

Related Questions