Php 在列出标签wordpress时删除最后一个逗号
我有下面的脚本来列出一篇文章中没有链接的标签,但是它在所有标签(包括最后一个)后面加了一个逗号。有没有办法阻止脚本在列表中的最后一个标记中添加逗号?我试着研究它,但是关于这个特殊的wp字符串,真的没有太多Php 在列出标签wordpress时删除最后一个逗号,php,wordpress,Php,Wordpress,我有下面的脚本来列出一篇文章中没有链接的标签,但是它在所有标签(包括最后一个)后面加了一个逗号。有没有办法阻止脚本在列表中的最后一个标记中添加逗号?我试着研究它,但是关于这个特殊的wp字符串,真的没有太多 <?php $posttags = get_the_tags(); if ($posttags) { foreach($posttags as $tag) { echo $tag->name . ', ';
<?php
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name . ', ';
}
}
?>
使用rtrim。它将修剪最后指定的字符
$posttags = get_the_tags();
if ($posttags) {
$taglist = "";
foreach($posttags as $tag) {
$taglist .= $tag->name . ', ';
}
echo rtrim($taglist, ", ");
}
更改逗号的位置,并设置一个小条件
<?php
$posttags = get_the_tags();
if ($posttags)
{
$first=true;
foreach($posttags as $tag)
{
if($first)
{
echo $tag->name;
$first=false;
}
else
{
echo ', '.$tag->name;
}
}
}
?>
当我需要处理数量可变的元素时,我倾向于这样做
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$temp[] = $tag->name;
}
}
if (!empty($temp)) echo implode(', ',$temp);
你需要wordpress功能。它将回显一个标记,因此您不需要整个循环。我还没有测试它,但我担心它不起作用,因为最正确的字符不是
,
;)如果我添加该行来代替当前的If,则不会显示任何标记。@ThomasNolan当你做什么?!O_o@KingCrunch-他试图内爆$posttags[n]->name我发现了我对你的错误。这个解决方案也能起作用。我删除了第一次尝试实现它时不应该删除的内容。对不起@janenz00更新。嗯,有点难看(不是每个人都喜欢array_-map()
),但想法应该很清楚:)使用infrade()
(因为这就是它存在的原因)。是的,我需要整个循环,因为我不希望在使用这些_标记时,与标记相关联的超链接被回响,那我的回答就没用了
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$temp[] = $tag->name;
}
}
if (!empty($temp)) echo implode(', ',$temp);