Fastest way to loop through all posts?

I need to run a background process in a plugin that does some work on ALL the posts in a person’s database once the plugin is installed. I’m very new at working with wordpress so my research has shown that I can use the wp query or I can use “the loop”.

Since I’m going through absolutely every single post speed is of the essence. I need to check the title, body, categories, meta tags, publish state and password protected. So based on this, which one of these would be fastest?

2 Answers
2

“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