tags:

views:

64

answers:

3

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) :
  setup_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?

A: 
<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>
Borealid
+3  A: 

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

Ben
Thanks Ben 10! real super fix. `:?> class` need to have a white space.
kampit
good point. fixed
Ben
+1  A: 
<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 :)

Sadat
I'm not sure if an array look up is faster than a conditional test :) Also, you probably don't need $curr_class, you could just use $i%2 as the index.. and the array should probably be array('even_class', 'odd_class')
Ben
I have made the odd/even class selection technique. I have said - "You need no Conditional statement :)", because of your last row selection condition, at least I have avoided that one easily :). Not about odd/even.
Sadat