WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 2 down vote accepted

This should do it:

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

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.

share|improve this answer
To summarize the solution and to make an appendum: The answer was to use a counter and check the value of that counter with each iteration of the loop. For styling based on post id(or similar) you'd have no need for such code, because post specific styling is already possible with the post_class(). – t31os Dec 16 '10 at 17:52
@t31os: Except that post_class() doesn't address this particular problem (ie. order specific styling), and I could not find anything in the core code that did. – Peter Rowell Dec 17 '10 at 1:48
John's answer addresses the question, i was simply pointing out that if post specific styling(by category, id or whatever) was required(and not a count specific style) that the post_class would cover it(incase anyone reading is looking for ID/cat/tag based styling, etc..). – t31os Dec 17 '10 at 10:03

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.