如何显示有限数量的标签?

时间:2017-02-19 13:18:22

标签: php wordpress wordpress-theming

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

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

我想要的:

enter image description here

1 个答案:

答案 0 :(得分: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)
    }
}