Category List With Comma & Link

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!

Related posts

Leave a Reply

2 comments

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