3

我有以下脚本来列出没有链接的帖子标签,但它在所有标签(包括最后一个标签)之后放置了一个逗号。有什么方法可以防止脚本在列表中的最后一个标签中添加逗号?我尝试研究它,但是关于这个特定的 wp 字符串真的没有很多。

<?php
    $posttags = get_the_tags();
    if ($posttags) {
        foreach($posttags as $tag) {
            echo $tag->name . ', '; 
        }
    }
?> 
4

5 回答 5

5

使用 rtrim。它将修剪最后一个指定的字符。

    $posttags = get_the_tags();
    if ($posttags) {
       $taglist = "";
       foreach($posttags as $tag) {
           $taglist .=  $tag->name . ', '; 
       }
      echo rtrim($taglist, ", ");
   }
于 2013-01-03T19:37:55.990 回答
3
if ($posttags) {
    echo implode(
        ', ', 
        array_map(
            function($tag) { return $tag->name; },
            $posttags
        )
    );
}
于 2013-01-03T19:35:20.840 回答
1

当我需要连接可变数量的元素时,我倾向于这样做。

$posttags = get_the_tags();
if ($posttags) {
    foreach($posttags as $tag) {
        $temp[] = $tag->name; 
    }
}
if (!empty($temp)) echo implode(', ',$temp);
于 2013-01-03T19:49:59.680 回答
0

更改逗号的位置并放置一个小条件

<?php
    $posttags = get_the_tags();
    if ($posttags)
    {
        $first=true;
        foreach($posttags as $tag) 
        {
            if($first)
            {
                echo $tag->name; 
                $first=false;
            }
            else
            {
                echo ', '.$tag->name; 
            }
        }
    }
?> 
于 2013-01-03T19:49:07.203 回答
0

您需要 wordpress 功能the_tags。它会回显一个标签,因此您不需要整个循环。

于 2013-01-03T19:51:36.297 回答