Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Trying to list the categories for post separated by a comma with link to the category archive.

                <?php
                foreach((get_the_category()) as $category) {
                if($category->name==$homecat) continue;
                $category_id = get_cat_ID( $category->cat_name );
                $category_link = get_category_link( $category_id );
                echo '<span class="cat"><a href="'.$category_link.'">'.$category->cat_name.'</a></span>';
                } ?>

Thanks for any help!

share|improve this question

2 Answers 2

up vote 1 down vote accepted

You can use the_category if you are in the loop:

<?php the_category(', '); ?>

If not, then use this code:

<?php
$output = '';
foreach((get_the_category()) as $category) {
    if($category->name==$homecat) continue;
    $category_id = get_cat_ID( $category->cat_name );
    $category_link = get_category_link( $category_id );

    if(!empty($output))
        $output .= ', ';
    $output .= '<span class="cat"><a href="'.$category_link.'">'.$category->cat_name.'</a></span>';
}
echo $output;
?>
share|improve this answer
    
That worked great, Ali! Thanks a lot :) –  Justin Nov 24 '11 at 19:32
    
Thanks Ali, I just used your great little piece of code myself for a project. Elegant solution to the "add comma or not"? problem, much better than what I usually use :-) –  Lars Koudal Nov 25 '11 at 12:33

If you are in the loop you can use the_category http://codex.wordpress.org/Function_Reference/the_category

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.