Adding a Class to Every nth Post

A project I was working on recently had a series of sections on a page. They ran in 3’s in that the 1st, 4th, 7th and so on and the 2nd, 5th, 8th (you get the idea!) were styled the same. Therefore I needed a way to add a class to each div which indicated which section it was. Here is how I did it.

I was able to create a loop (we use them a lot in WordPress!) and then use a counter to find out which section were we in, in order to add the correct class. The code I used is below:

As you can see this uses the PHP operator modulus, which would check out on the PHP site here.

You could of course adapt this to suit other patterns of post classes, quite easily.

Published by

Mark Wilkinson

Lead developer & owner at Highrise Digital @highrisedigital. Develops the @wpbroadbean plugins. Former teacher.

2 thoughts on “Adding a Class to Every nth Post”

  1. Excellent. Would you please tell me how can i display different featured image in the loop for every nth post? What i mean is, i have to show a different featured image on the home page for every 3rd post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s