I tried to figure out how to separate the custom post type taxonomies.

$terms = get_the_terms( $post->ID , array( 'commitments', 'type' ) );
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>';
}

Each taxonomies show correctly. However, I cannot separate them in comma. it shows “TaxonomyATaxonomyB” but I want to show it as “TaxonomyA, TaxonomyB”

How to do it? or is there any other way around?

Thanks!

3 Answers
3

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 Reply

Your email address will not be published. Required fields are marked *