[英]Php : How to add odd/even loop to my unordered list
这是我的wordpress帖子的示例。 我想在<li>
的最后添加一些类
类似于<li class='lastli'>
<ul class="tabs">
<?php
global $post;
$myposts = get_posts('numberposts=3');
foreach($myposts as $post) :
setup_postdata($post);
?>
<li><a href="#"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
我想要的结果是:
<ul>
<li>Title 1</li>
<li>Title 1</li>
<li class='lastli'>Title 1</li>
<ul>
最后的无序列表将是<li class='lastli'>
。 让我知道该怎么做?
使用for循环
<ul class="tabs">
<?php
global $post;
$myposts = get_posts('numberposts=3');
$nposts = count($myposts);
for($i=0;$i<$nposts;$i++):
$post = $myposts[$i];
setup_postdata($post);
?>
<li<?php if ($i==$nposts-1):?> class='lastli'<?php endif;?>><a href="#"><?php the_title(); ?></a></li>
<?php endfor; ?>
</ul>
注意:在循环之前计算数组大小是一个好习惯,否则php将在循环的每一轮对其进行评估
<ul class="tabs">
<?php
global $post;
$myposts = get_posts('numberposts=3');
$nposts = count($myposts);
$odd_even_class = array('odd_class', 'even_class');
for($i=0;$i<$nposts-1;$i++):
$post = $myposts[$i];
setup_postdata($post);
?>
<li <?php echo $odd_even_class[($i+1)%2];?>><a href="#"><?php the_title(); ?></a></li>
<?php
endfor;
$post = $myposts[$i];
setup_postdata($post);
<li class='lastli'><a href="#"><?php the_title();?></a></li>
</ul>
您不需要条件语句:)
<ul class="tabs">
<?php
global $post;
$myposts = get_posts('numberposts=3');
$i = 0;
for ($i = 0; $i < count($myposts); $i++) {
$post = $myposts[$i];
setup_postdata($post);
?>
<li <?= ($i==count($myposts)-1)?"class='lastli'":"" ?>><a href="#"><?php the_title(); ?></a></li>
<?php } ?>
</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.