Hello all. Welcome to 2012! For my first post of the year, I’m going to show you a little trick I learned using PHP post-count functions to style my WordPress posts differently based on the post count – i.e. where that post falls in the numbered order (in relation to the other posts).

For example, you’ll be able to use this script to make sure that your most recent post has different styling than your second-most recent, and your second-most recent can be styled differently than your third.

Furthermore, you can use this script to style your WordPress category and search archives differently as well.

There are several files within your WordPress template where you can plug this script in if you want to count your posts and style them accordingly:

  • loop.php
  • index.php
  • archive.php
  • author.php
  • category.php
  • search.php
  • tag.php

Why is this script worthwhile? A couple reasons:

  1. It gives you the opportunity to jazz up your post loop by styling each post differently.
  2. Good design is a hallmark of memorable sites, and this gives you the chance to make your design unique from other sites.
  3. Allows you the flexibility to do things such as adding website ads and more right in the middle of your loop.
  4. I’m sure there’s much more…

So, let’s get to the code.

The Beginning

Here is the first part of the script:

As you can see, this template will begin working if you have posts. If you have any posts, it will begin counting them starting at 0.

The Meat

Here is the next part of the script that lets you begin to count and style the posts.

You can pretty much keep repeating and renumbering the elseif loop infinitely (or until you run out of posts). The idea is, if you have 1 post, it will show it. If it is found that you have two posts, it will show both. If you have three posts, it will show three. If four, it will show four, and so on and so forth all the way up until the point where you’ve designated as a stopping point.

If you are using this script on your category archive page and stop the loop at say 10 posts, but there are 20 in the category that you’re showing. It will show and style the first 10, and then after that point, you can use a pagination script to show the next 10 (or however many). I’d recommend the WP-Paginate WordPress Plugin for this.

Wrapping It Up

Here is the code that stops the loop and wraps it all up:

A nice little close.

The Whole Thing

And now here is the whole script together:

Keep in mind, most of the templates will utilize the WordPress loop, so you can either edit the loop or overwrite it in the other files. I prefer to overwrite the loop in the various files to ensure maximum control and flexibility in how my posts are displayed and styled.

Here is the blank CSS:

.item1 {
.item2 {
.item3 {
.item4 {
.item5 {

That’s it. Hope you enjoyed the script, and have fun using it in your WordPress template. Happy 2012 all!