WordPress.org

Forums

[resolved] how to remove add a comma to a list of category names (3 posts)

  1. andrewtoohill
    Member
    Posted 2 years ago #

    I am using this code to not display a specific category name in the category list:

    <?php
                                  foreach((get_the_category()) as $category) {
                                     if ($category->cat_name != 'Featured') {
                                        echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> ';
                                     }
                                  }
                               ?>

    I need to know how to add a comma after each category name but not on the last category that is listed. Any thoughts?

  2. alchymyth
    Forum Moderator
    Posted 2 years ago #

    possibility A:

    <?php $cats = array();
                                  foreach((get_the_category()) as $category) {
                                     if ($category->cat_name != 'Featured') {
                                        $cats[] = '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> ';
                                     }
                                  }
      echo implode(', ', $cats);                         ?>

    possibility B:

    <?php $separator = '';
                                  foreach((get_the_category()) as $category) {
                                     if ($category->cat_name != 'Featured') {
                                        echo $separator . '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> ';
    $separator = ', ';
                                     }
                                  }
                               ?>
  3. andrewtoohill
    Member
    Posted 2 years ago #

    Thank-you. Both of those worked. I had to remove the space after the closing of the anchor tag so that the comma was directly after the name of the category and didn't have a space before and after them. Thank-you for your help!

Topic Closed

This topic has been closed to new replies.

About this Topic