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.
@Tarendai You’re missing a section, after “We can apply Iterator logic to this too, giving us this:”. Suspense is killing me 🙂
@stephenharris88 Im not missing a section, http://t.co/YecRKsaL84 is having service issues
@Tarendai My mistake, its back now :). Odd that it affected only one of the gists…
RT @Tarendai: Alternative WP Post Loops http://t.co/wMLKKdz9T5 #wordpress
Wow – that makes the general purpose WP code so much simpler, even I can follow it.
RT @Tarendai: Alternative WP Post Loops http://t.co/wMLKKdz9T5 #wordpress
RT @Tarendai: Alternative WP Post Loops http://t.co/wMLKKdz9T5 #wordpress
This is very nice! Thanks for sharing!
Very nice!
But does it work with there is no post found or if you need a second loop?
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 callhave_posts
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;
I love it. That’s how I like to code in WordPress, more in the PHP native way than the WP way 🙂