Limit number of posts with WordPress

February 26, 2005

One of the first things I noticed when I started to setup WordPress was that there was no way to control the number of posts displayed on the index page from the admin panel. Yes, there is the "Show at most" option, but this is a site-wide variable and works to treat all of your pages the same — I didn't want that.

So, as things sometimes go on this site, I didn't plan to post a workaround to this (it's kind of trivial), but I've had a few people ask me how to do it and so I thought I'd explain it here both for them and for future Google traffic.

Why I Wanted This

All of this stems from the fact that I don't usually like "next 10 posts" / "previous 10 posts" links and didn't want them on my website. Rather, I like whatever archives page the user is on (be it yearly, monthly, or daily) to display all of the posts for that particular time span. This can be achieved rather easily by setting the "Show at most" option to something very large (i.e., a number at least as large as the number of posts on your "largest" page). The problem is that this number will also be used to control the number of posts on your index page.

The Fix

To limit the number of posts on your index page while allowing all other pages to look to the "Show at most" setting, you simply need the following lines of code.

<?php static $ctr = 0; 
if ($ctr == "X") { break; } 
else { ?>

You'll want to place this code directly inside the main loop you use to display the posts on your index page. The regular PHP and/or HTML that actually forms these posts should be placed inside the open "else" shown in the above code. You should then close the "else" with a curly bracket ("}"). Change the "X" in my example to the number of entries you want displayed.

Because you need to increase the "ctr" variable by one each iteration through the loop, you'll need to put the following code right before the loop is terminated.

<?php $ctr++; } ?>

It's that simple. After this code is up and running, your index page will display the first X entries and your archive pages will display the number of posts as defined by "Show at most."

You should follow me on Twitter here