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 |1 Answer
Reset to default 2Your 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 implode
ing 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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742314426a4420549.html
implode
after theendforeach
– s_ha_dum Commented Jun 12, 2015 at 3:06foreach
– s_ha_dum Commented Jun 12, 2015 at 3:29$typeName = array();
beforeforeach loop
and use '<?php echo implode(',', $typeName); ?>' afterendforeach;
– sohan Commented Jun 12, 2015 at 6:55