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?
“The Loop” is just a name given to the
while (have_posts()): the_post();
loop used to iterate over an array of posts returned byWP_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 aforeach
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 callsetup_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.
“The loop” is just a name applied to a foreach loop applied to a WP_Query object.
So you need both. Typically the loop also includes the_post() so that you can use template tags.
There’s another option though, that may be faster. Depending on what you need to do, you could do a direct database query to retrieve just the fields you want to edit. But since you also need categories and meta tags it would be a complicated join. For easier updates and backward compatability, you may as well use the regular WP_Query.