WordPress loops: with_posts() is my way of dealing with them

One of the most boring, cumbersome and dangerous things with WordPress is getting and working with posts in custom loops.

A common situation is like this:

That’s a bit cumbersome I think. Do I really need to do that while-thingie, that the_post()-method-thingie and that wp_reset_postdata()-thingie each time? It feels a bit… repetitive. And dangerous, since if I forget to reset the postdata I can screw up other loops and functions and plugins and my site (that often is a client site..) is starting to fall apart, loop by loop.

with_posts(): a fancy solution with a callback

So, I give you my solution to this problem: the with_posts()-function. Let’s do the same thing again, using my approach:

Using with_posts() I went from 6 lines to 3 lines.

Maybe it’s just 3 lines less you think, but hey it’s 3 lines less every time you want to loop something! That, plus you won’t forget that reset_postdata or setup_postdata thing again.

The magic is in the callback function: inside it you will automagically get the current post as the current post and it’s called once for each post in the matching query. You can use all the common stuff like the_title, the_permalink, edit_post_link, the_content, and so on.

Oh! And you can pass other stuff into the with_post-function too (ids, slugs, query strings…), to get any mix of posts. This example uses a regular wp_query as the base, to get some posts from a custom post type:

The function is posted in a Gist on Github for your viewing and forking pleasure, and I’ve also created a Gist with all kinds of  examples, so check it out and you’ll probably hopefully get the hang of it.

What can i say – I love this little function, and I hope you do.

Now, feedback me!