WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] cat_name comma seperated (3 posts)

  1. anthonyb
    Member
    Posted 3 years ago #

    I'm currently trying to display categories from each post and was hoping to seperate each category link by a comma, except or the last category.

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

    Any ideas?

  2. alchymyth
    The Sweeper & Moderator
    Posted 3 years ago #

    for instance:

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

    the added code is using a separator string $sep, which is echoed before the linked cat_name; it starts off as an empty string '', and gets set to comma and space ', ' after the first cat_name.

  3. anthonyb
    Member
    Posted 3 years ago #

    Hey alchymyth,

    This worked out quite well! Thank you for the quick response!

    Cheers,
    Anthony

Topic Closed

This topic has been closed to new replies.

About this Topic