【问题标题】:How to display limited number of tags post?如何显示有限数量的标签帖子?
【发布时间】:2017-02-19 13:18:22
【问题描述】:

我有一个带有标签的帖子:b1、b2、b3。但是在类别模板中,我只想为帖子显示 2 个标签:b1,b2。我该怎么做 ? 现在我使用以下代码来显示帖子的标签:

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

我想要什么:

【问题讨论】:

  • 视情况而定。您是否过滤掉 b3 因为它是最后一个标签?还是因为您的标签限制为 2?还是因为 b3 的实际标签值?还是别的什么?
  • 我只需要显示 2 个标签。仅限于 2 个@mickmackusa

标签: php wordpress wordpress-theming


【解决方案1】:

更新:返回到 foreach() 并中断。

<?php
$posttags = get_the_tags();
if($posttags){
    foreach($posttags as $index=>$tag){
        echo '<li>' .$tag->name. '</li>'; // echos while $index == 0 & 1
        if($index>0){break;}  // second iteration ($index==1) breaks the loop
    }
}
?>

或者如果 $posttags 数组不使用数字键,您可以创建自己的迭代计数器:

if($posttags){
    $x=0;
    foreach($posttags as $tag){
        echo '<li>' .$tag->name. '</li>'; 
        if(++$x==2){break;}  // increment and test $x (first $x=1, second $x=2 so break)
    }
}

【讨论】:

猜你喜欢
  • 2012-02-27
  • 2019-11-09
  • 2013-11-01
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 2020-02-18
  • 2021-05-18
  • 1970-01-01
相关资源
最近更新 更多