【问题标题】:Wordpress: How to add commas in this get_the_terms functionWordpress:如何在这个 get_the_terms 函数中添加逗号
【发布时间】:2018-07-11 01:14:02
【问题描述】:

我正在使用这个功能:

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

但是我将术语视为术语 1、术语 2、术语 3(末尾还有一个逗号),我如何在不需要时用逗号显示术语但不使用逗号?

【问题讨论】:

标签: php wordpress


【解决方案1】:

您应该将它们全部存储到一个数组中,然后使用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);
    }
}

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

【讨论】:

  • @MiguelZafra 很高兴我能提供帮助!
【解决方案2】:

如果您不想使用数组,请使用以下内容:

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

echo trim($string, ", ");

【讨论】:

    【解决方案3】:

    您可以使用 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;
    

    【讨论】:

      【解决方案4】:

      省略所有检查,这可以减少到一行。

      // Get terms for post
      $terms = get_the_terms($post->ID, 'skills');
      
      echo implode(", ", array_map(function($T) {return is_a($T, 'WP_Term') ? $T->name : false; }, $terms ))
      

      与 array_column 类似,但使用对象

      【讨论】:

        猜你喜欢
        • 2014-05-11
        • 1970-01-01
        • 1970-01-01
        • 2017-07-15
        • 1970-01-01
        • 1970-01-01
        • 2019-07-06
        • 1970-01-01
        • 2014-01-24
        相关资源
        最近更新 更多