基于一些引用,我构建了一个函数来输出由逗号分隔的自定义分类术语列表。代码按预期工作,其中food_tag 是我为自定义post\\u类型注册的自定义分类法。
功能如下:
function get_taxonomy_food_tags(){
 $terms = get_terms(\'food_tag\');
 foreach($terms as $term){
 // The $term is an object, so we don\'t need to specify the $taxonomy.
 $term_link = get_term_link($term);
 $numItems = count($terms);
 $i        = 0;
 // If there was an error, continue to the next term.
 if (is_wp_error($term_link)){
      continue;
 }
 // We successfully got a link. Print it out.
 echo \'<a href="\' . esc_url($term_link) . \'">\' . $term->name . \'</a>\';
 if (++$i != $numItems) {
            echo \', \';
 }
 }
}
 然后我放置代码
<?php get_taxonony_food_tags(); ?> 在我的主题中的任何地方。php模板,我得到一个带有链接的自定义标记列表。例如:
Ingredients: Bacon, Tomato Slices, Tomato Sauce, Lettuce, Beef,
结果表明,数组中的最后一个标记也是用逗号打印的
如何正确设置函数以排除最后一个逗号?
提前谢谢。
 
                SO网友:Eduardo Sánchez Hidalgo Urías
                问题是,每次foreach循环执行时,您都将0作为$i的值,因此,当最后一个if语句执行时,每次比较都是1!=3,并且始终打印逗号。尝试声明$i=0;foreach循环外部。像这样:
$terms = get_terms(\'food_tag\');
$i = 0;
foreach($terms as $term){ 
//the code here
}
 此外,末尾缺少一个花括号,这可能只是复制粘贴错误,但对于那些试图复制粘贴并使其运行的人来说。