Add first and last classes to your loop without using JavaScript

So you’re a pixel-perfect designer who wants to keep control over your WordPress loop styles? Hell yeah! You’re already pretty cool in my book.

You’ve probably got a fancy post separator, or a brilliant doodle to fit between your last post and the comments. Whatever the reason, you don’t have CSS class selectors for targeting the first or last posts in your archive – and you really need them.

There are a lot of tutorials on how to achieve this with jQuery. But it’s not worth relying on JavaScript for something that can easily be done with a little PHP magic.

First, insert this function into your functions.php file.

Now, open up loop.php and replace post_class() with the newly created fjarrett_post_class().

This new function accepts the same parameters as the original function, so you can use it the exact same way. The only difference will be that the first and last posts will be marked automatically with an appropriate class name. Enjoy total control. :)

If this helped you in any way I’d love to hear about it in the comments!


Add yours →

  1. thanks! this works perfect!!

  2. Great job I searched far and wide and found nothing, till I found this worked just as is thank you.

  3. Worked great! Thanks!

  4. Just what I needed! Thank you!

  5. Hello, I add your code that works in my theme for posts basic, but it works only in one type else custom post, I do not know how to blow.

Leave a Reply

%d bloggers like this: