Php : How to add odd/even loop to my unordered list
Here an example my wordpress post. I want to add some class to the last of <li>
something like <li class='lastli'>
<ul class="tabs">
<?php
global $post;
$myposts = get_posts('numberposts=3');
foreach($myposts as $post) :
set开发者_如何学JAVAup_postdata($post);
?>
<li><a href="#"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
The results I wanted to be like :
<ul>
<li>Title 1</li>
<li>Title 1</li>
<li class='lastli'>Title 1</li>
<ul>
Any last of unordered lists will be <li class='lastli'>
. Let me know how to do that?
use a for loop
<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>
Note: counting your array size before the loop is good practice, otherwise php will evaluate it at every round of the loop
<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>
You need no Conditional statement :)
<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>
精彩评论