Treehouse: Grow your CSS skills. Land your dream job.

Using “Last” Class In The Loop (WordPress)

  • # June 2, 2011 at 11:40 am

    Hey Ya’ll,

    I’ve got an unordered list displaying my pages in The Loop. Each list item has a margin-right of 20px and I need to rid the right margin off every fourth item in that list. Now, normally I’d use a class of “last” on the fourth item of the list and set the margin to 0. Since I’m doing this in The Loop how would I achieve something like this?

    This is how my code looks at the moment:

      < ?php query_posts('post_type=page'); ?>
      < ?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    • < ?php the_post_thumbnail(); ?>
      < ?php the_title(); ?>
      < ?php the_permalink(); ?>">

    • < ?php endwhile; endif; ?>

    I was thinking of adding < ?php the_ID(); ?> to the class of the list item. This works but adds a lot of unnecessary code. I’d like every fourth item to have a class of last, is this possible?

    Any help would be appreciated, thanks in advance.

    UPDATE: Solved it, for those interested:

    Put this in your functions.php file:

    function switchClass($n, $i, $prefix = '')	{
    $output = '';
    if (is_numeric($n)) {
    if ($i % $n == 0) {
    $output = ' '.$prefix.'last';
    return $output;

    This is your loop. Here it’s echoing the class “first” on every fourth list item (see line 4).

      < ?php query_posts('post_type=page'); ?>
      < ?php if ( have_posts() ) : $i = 1; while ( have_posts() ) : the_post(); ?>

    • < ?php $i++; endwhile; endif; ?>

    For more info on this implementation check out

    # June 2, 2011 at 1:37 pm

    Pseudo-elements with CSS.

    You’re looking for :last-child

    # June 2, 2011 at 2:01 pm

    @TheDoc I was under the impression IE doesn’t support this.

    # June 2, 2011 at 2:08 pm

    It looks like you’ve found a pretty good solution, but since you’ll probably be slapping on some JS to help IE anyways, might as well go the CSS3 route (at least that’s what I would do).

    Here’s a pretty good looking list of browser support:

    # June 2, 2011 at 2:29 pm

    Cheers @TheDoc, I’ll give it a try. Any idea on how I’d make my sub-pages loop in alphabetical order?

    # June 2, 2011 at 2:30 pm

    @TheDoc, Don’t worry. Found it:

    # October 18, 2011 at 6:28 am

    Hi. Sweet solution. works perfectly. thanks for sharing

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.