Support » Fixing WordPress » cat_name comma seperated

  • Resolved anthonyb

    (@anthonyb)


    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?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Michael

    (@alchymyth)

    Forum Moderator

    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.

    Hey alchymyth,

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

    Cheers,
    Anthony

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘cat_name comma seperated’ is closed to new replies.