admin管理员组

文章数量:1336079

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:

<?php
  $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.

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:

<?php
  $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.

Share Improve this question asked Jun 12, 2015 at 2:43 ultraloveninjaultraloveninja 2291 gold badge7 silver badges18 bronze badges 5
  • Put the implode after the endforeach – s_ha_dum Commented 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. – ultraloveninja Commented 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 Commented Jun 12, 2015 at 3:29
  • This is very basic php which belongs on Stack Overflow :-) – Pieter Goosen Commented Jun 12, 2015 at 4:28
  • try to put $typeName = array(); before foreach loop and use '<?php echo implode(',', $typeName); ?>' after endforeach; – sohan Commented Jun 12, 2015 at 6:55
Add a comment  | 

1 Answer 1

Reset to default 2

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

本文标签: custom post typesCommas not displaying in implode