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.