Alternative Post Loops

We all know the standard post loop in every template, but what if we did something slightly different?

Lets begin with the standard main loop we all know:

View the code on Gist.

There’s a lot of boilerplate there, what if we could reduce it down? Lets try using a feature of PHP 5 called Iterators:

View the code on Gist.

Put the class in your functions.php and you can replace your post loops with a single foreach and a 1 liner to setup the loop. The calls to have_posts() and the_post() have all been removed, and the need to use code such as global $post; or get_the_id() are eliminated.

But not every post loop is a main loop, sometime we use WP_Query ( or get_posts(), but never query_posts() ). This is what a normal WP_Query loop looks like:

View the code on Gist.

We can apply Iterator logic to this too, giving us this:

View the code on Gist.

But the fun doesn’t stop there! If you’re lucky enough to be using the new PHP 5.5, you have a new feature called generators that allows you to do this:

View the code on Gist.

Using generators makes for a big reduction in code. A 7 line function can remove all the boilerplate from our post loops and have a single foreach loop with no setup step of any kind.

12 thoughts on “Alternative Post Loops

    • That depends on which one you’re talking about, they’re all analogous to standard post loops or WP_Query loops, so the same holds true of these as of the originals. For when no posts are found, the loop doesn’t run, and you can still call have_posts

  1. Amazing. I really love the generator format. Simple and beautiful.

    I’ve made a minor change (I don’t like to use the globals used internally by WordPress):

    while ( have_posts() ):
    yield get_post();

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.