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:

https://gist.github.com/wpmark/e969a5386589f7b57996

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.

2 responses

  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.

    1. Wouldn’t each post have a different featured image anyway?

Leave a Reply

Your email address will not be published. Required fields are marked *