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 |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
本文标签: custom post typesCommas not displaying in implode
版权声明:本文标题:custom post types - Commas not displaying in implode 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742314426a2451527.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