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.
Leave a Reply