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 responses to “Alternative Post Loops”

  1. David Coveney avatar

    Wow – that makes the general purpose WP code so much simpler, even I can follow it.

  2. littleguy avatar
    littleguy

    This is very nice! Thanks for sharing!

  3. Daniel avatar

    Very nice!

    But does it work with there is no post found or if you need a second loop?

    1. Tom J Nowell avatar

      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

  4. Cláudio Esperança avatar
    Cláudio Esperança

    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() ):
    the_post();
    yield get_post();
    endwhile;

  5. CR Compumania avatar

    I love it. That’s how I like to code in WordPress, more in the PHP native way than the WP way 🙂

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.