Wordpress:如何在此get_the_terms函数中添加逗号

时间:2018-01-31 19:56:15

标签: php wordpress

我正在使用此功能:

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
    foreach($terms as $term) {
        echo $term->name . ", ";
        unset($term);
    }
}

但是我看到术语为term1,term2,term3,(最后还有一个逗号),如何用逗号显示这些术语,但如果没有逗号则不用逗号?

3 个答案:

答案 0 :(得分:2)

不要在循环期间回显所有变量,而应将它们全部存储到数组中,然后使用implode()函数以所需格式回显它们。

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
    $output = array();
    foreach($terms as $term) {
        $output[] = $term->name;
        unset($term);
    }
    echo implode(", ", $output)
}

不想使用数组或变量?还有另一种解决方案。只需检查循环期间当前是否在数组中的最后一个元素上。

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
    end($terms);
    $endKey = key($terms);
    foreach($terms as $key => $term) {
        echo $key != $endKey? $term->name.", " : $term->name;
        unset($term);
    }
}

我将$key添加到foreach循环中,以便您可以与之进行比较。您可以通过end($array)然后使用key()获取实际密钥来获取数组的最终密钥。

答案 1 :(得分:0)

如果您不想使用以下数组:

$terms = get_the_terms($post->ID, 'skills');
$string = "";
if($terms != null) {
foreach($terms as $term) {
    $string .= $term->name . ", ";
    unset($term);
}
}

echo trim($string, ", ");

答案 2 :(得分:0)

你可以使用rtrim。 (来自php.net:从字符串末尾删除空格(或其他字符))

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
    $stringFinal = "";
    foreach($terms as $term) {
        $stringFinal = $term->name . ", ";
    }
    $stringFinal = rtrim($stringFinal, ', ')
}
echo $stringFinal;