Separate Custom Post Type Taxonomy by Comma

You can use a counter to determine if you need to add a comma or not :

$terms = get_the_terms( $post->ID , array( 'commitments', 'type' ) );
// init counter
$i = 1;
foreach ( $terms as $term ) {
    $term_link = get_term_link( $term, array( 'commitments', 'type' ) );
        if( is_wp_error( $term_link ) )
        continue;
        echo '<a href="' . $term_link . '">' . $term->name . '</a>';
        //  Add comma (except after the last theme)
        echo ($i < count($terms))? ", " : "";
        // Increment counter
        $i++;
}

Leave a Comment