Fastest way to loop through all posts?

“The Loop” is just a name given to the while (have_posts()): the_post(); loop used to iterate over an array of posts returned by WP_Query(). The other function used for querying posts is the get_posts() function, which returns a simple (non-extended) array which you can loop through with a foreach loop.

I don’t think it matters a whole lot; however, if you’re nitpicking, the get_posts() method is slightly faster and less memory-intensive, since it doesn’t call setup_postdata() (which populates the template tags, etc.) on every post it loops through.

Either way, you’re probably going to run out of memory on some setups with thousands of posts… Make sure you build in fallbacks in that case.

Leave a Comment