3

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!

2
  • try this for the echo : echo ', <a href="' . $term_link . '">' . $term->name . '</a>';
    – mmm
    Sep 6, 2016 at 12:05
  • it shows , in the first line of the text. it shows ", TaxonomyA, TaxonomyB". It should have "Join"
    – MightyGas
    Sep 6, 2016 at 12:13

3 Answers 3

6

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++;
}
1
  • This one works! thank you @Dexter0015 :) great help.
    – MightyGas
    Sep 6, 2016 at 12:42
7

Or you can use get_the_term_list function.

<?php echo get_the_term_list( $post->ID, 'commitments', '', ', ' ); ?>
3
  • This one works too. short and neat :)
    – MightyGas
    Sep 6, 2016 at 12:48
  • Only thing is I don't think you can pass multiple taxonomies to it Sep 6, 2016 at 13:37
  • Awesome, simple and easy :)
    – Jodyshop
    Oct 5, 2021 at 12:01
3

The cleanest way (IMO) to do anything like this in PHP, is build an array and then implode it:

$list = [];
foreach ( $terms as $term ) {
    $term_link = get_term_link( $term /* no need for taxonomy arg if $term is an object */ );
    if ( ! is_wp_error( $term_link ) )
        $list[] = $term_link;
}

echo implode( ', ', $list );
1
  • Far superior to using any type of count. Sep 25, 2020 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.