用逗号分隔自定义邮政类型分类

时间:2016-09-06 作者:MightyGas

我试图找出如何分离自定义的post类型分类法。

$terms = get_the_terms( $post->ID , array( \'commitments\', \'type\' ) );
foreach ( $terms as $term ) {
    $term_link = get_term_link( $term, array( \'commitments\', \'type\' ) );
        if( is_wp_error( $term_link ) )
        continue;
        echo \'<a href="\' . $term_link . \'">\' . $term->name . \'</a>\';
}
每个分类法都正确显示。然而,我不能用逗号分隔它们。它显示“TaxonomyATaxonomyB”,但我想显示为“TaxonomyA,TaxonomyB”

怎么做?或者还有其他方法吗?

谢谢

3 个回复
最合适的回答,由SO网友:Dexter0015 整理而成

您可以使用计数器确定是否需要添加逗号:

$terms = get_the_terms( $post->ID , array( \'commitments\', \'type\' ) );
// init counter
$i = 1;
foreach ( $terms as $term ) {
    $term_link = get_term_link( $term, array( \'commitments\', \'type\' ) );
        if( is_wp_error( $term_link ) )
        continue;
        echo \'<a href="\' . $term_link . \'">\' . $term->name . \'</a>\';
        //  Add comma (except after the last theme)
        echo ($i < count($terms))? ", " : "";
        // Increment counter
        $i++;
}

SO网友:99teko

或者您可以使用get_the_term_list 作用

<?php echo get_the_term_list( $post->ID, \'commitments\', \'\', \', \' ); ?>

SO网友:TheDeadMedic

在PHP中执行类似操作的最干净的方法(IMO)是构建一个数组,然后将其内爆:

$list = [];
foreach ( $terms as $term ) {
    $term_link = get_term_link( $term /* no need for taxonomy arg if $term is an object */ );
    if ( ! is_wp_error( $term_link ) )
        $list[] = $term_link;
}

echo implode( \', \', $list );

相关推荐

GET_THE_TERMS与wp_GET_POST_TERMS中的奇怪结果

我正在尝试制作一个面包屑函数,但有一个小问题。。。使用时:$categories = get_the_terms( $post->ID, \'product_cat\' ); 我得到了一个循环中使用的类别数组,等等。唯一的问题是它是按字母顺序排列的。(我希望它按层次顺序排列。)经过一番挖掘,我发现了一种替代方法,即使用wp\\u get\\u post\\u terms(),但我肯定遗漏了一些东西,因为当我使用此方法时:$categories = wp_get_post_terms( $p