How to track post number on the_loop

I have a need to customize some posts from the loop.
Here’s the deal: My site is set to 10 posts per page.
On post #2,#5, #7 (on every page), I want to display specific background.
What’s the best solution for this kind of problem?

Related posts

Leave a Reply

2 comments

  1. This should do it:

    $real_current_post = $wp_query->current_post + 1;
    switch( $real_current_post ){
      case 2:
        // Do something for 2
        break;
      case 5:
        // Do something for 5
        break;
      case 7:
        // Do something for 7
        break;
    }
    

    You may need to globalize $wp_query, but as long as you’re using the normal template hierarchy, it should already be in scope. If you do use global $wp_query;, use it before the loop starts.

  2. One way of handling this is to use CSS pseudo classes. On the plus side it keeps you from making hardwired decisions in your loop code, on the down side it won’t work in older/broken browsers, ie. MSIE 6.

    div#content div.post:nth-child(2),
    div#content div.post:nth-child(5),
    div#content div.post:nth-child(7) {
    background-color: #FF0; }

    If you like this approach but it must work in all browsers, then you can do the above in jQuery. Although I try to make major design elements degrade gracefully when dealing with dinosaurs like IE6, I’ve stopped catering to it for stuff like this. The majority of its users are either inside corporate LANs or are severely lagging end-users, neither of which are in our main demographics.