I recently decided that i should dramatically improve the queries in my WordPress plugins. That’s a good thing. And i encourage you to do the same. Basically, we all do queries: in themes, in plugins, in templates files etc… Even if those queries, most of the time, work well, they could be improved with under-used parameters.
A basic Query
Just for those of you who aren’t that used to the WP_Query class, here is a quick reminder of how to use it in a basic example:
What this code do is listing posts and placing them in an unordered list. But, well, to be a bit better the $args array should have some attributes. Let’s say, that we want to list posts from categories 1, 6 and 8, and written by “John”. We want only 5 posts to be listed. Then the query would look to something like this:
A better Query
But let’s say, in a specific query, you only need to retrieve post IDs and no other element such as post meta. In that particular case, you could improve the query performance by adding a simple argument in $args : fields:
That’s much better. This query is loading only post IDs that match our arguments. Loading performance is now much better.
Querying only the necessary
And finally, let’s say that you want want to use the post fields but not the post meta (from wp_postmeta table) and and not the post terms. That’s pretty easy, simply add “update_post_meta_cache” and “update_post_term_cache” set to “false” in the query arguments. That way, only fields from the main post SQL table will be loaded. If your theme uses many post meta and that you don’t need to load them in a query use this method:
This is what how in the codex is explained the use of these two parameters:
In general usage you should not need to use these, adding to the cache is the right thing to do, however they may be useful in specific circumstances. An example of such circumstances might be when using a WP_Query to retrieve a list of post titles and URLs to be displayed, but in which no other information about the post will be used and the taxonomy and meta data won’t be needed. By not loading this information, you can save time from the extra unnecessary SQL queries.
Note: If a persistent object cache backend (such as memcached) is used, these flags are set to false by default since there is no need to update the cache every page load when a persistent cache exists.
Well, this was a quick introduction to how to improve your queries performance. I’ll be covering this part more in depth at WordCamp Paris, for those who will be there, don’t hesitate to ask questions in the comments section, and i’ll answer at the WordCamp.