I'm trying to separate some taxonomy terms with a comma, but I can't see to get the commas to show correctly.

Here's what I got:

  $terms = get_the_terms($post->ID,'type');
  foreach ( $terms as $term ) :
    $typeName = array();
    $typeName[] = $term->name;
    <small><?php echo implode(', ', $typeName); ?></small>
  <?php endforeach; ?>

They seem to echo out just fine. Just can't get the commas to show.

  • Put the implode after the endforeach
    – s_ha_dum
    Jun 12, 2015 at 3:06
  • Hmmm, if I do that then it only lists out one of the term names and not all term name that are checked for that custom post type. Jun 12, 2015 at 3:27
  • You are resetting the array at every iteration as well. Move that variable definition to before the foreach
    – s_ha_dum
    Jun 12, 2015 at 3:29
  • This is very basic php which belongs on Stack Overflow :-) Jun 12, 2015 at 4:28
  • try to put $typeName = array(); before foreach loop and use '<?php echo implode(',', $typeName); ?>' after endforeach;
    – sohan
    Jun 12, 2015 at 6:55

1 Answer 1


Your problem is that you are defining the $typeName variable as an empty array at the stat of each iteration of the loop, effectively erasing it, then filling that empty array with a single term name, which you implode. You don't see any commas because you are implodeing a one term array. Move the definition to before the Loop and the implode to after it.

$terms = get_the_terms($post->ID,'category');
$typeName = array();
foreach ( $terms as $term ) {
  $typeName[] = $term->name;
} ?>
<small><?php echo implode(', ', $typeName); ?></small><?php

That said, there are more Wordpress-ie ways to do this. WordPress provides a function called wp_list_pluck() that will shorten your labor:

$terms = get_the_terms($post->ID,'category');
$typeName = wp_list_pluck($terms,'name'); ?>
<small><?php echo implode(', ',$typeName) ;?></small><?php

get_the_term_list() may also work for you, though you get hyperlinks and not bare term names:

$terms = get_the_term_list( $post->ID, 'category', $before = '', $sep = ', ', $after = '' ); ?>
<small><?php echo $terms; ?></small><?php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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