When working on WordPress based projects we always use get_posts() or WP_Query() to get posts and its details. But there are some situations when we need to optimize query more for faster response. Lets consider a situation where we want to display some post related data through AJAX (say: the post’s title and its publish date) in an auto complete box. In this case we need to fetch the posts as much fast as we can. How can we achieve faster reponse from WP query ?
Before that, lets see what excatly taking more time to fetch and provide response. If you see the execution flow and the functions being called in XDEBUG PROFILER, for get_posts() or new WP_Query(), it always try to keep the fetched data inside Cache which is unnecessary for the above situation. What can we do to optimize this query execution and stop updating the Cache which we are not going to use in future. For reference, if you see the below snapshot, the actual function get_results() used to talk to database and fetch the post details takes less time( 263 ms ) whereas update_post_caches() function takes way more time ( 16,982 ms ).
[ Click on the image to have a large & clear preview ]
Here are some parameters that we can use to optimize the WordPress query.
$post_query = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC', 'no_found_rows' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'cache_results' => false ) );
- no_found_rows (boolean) – make it true when you don’t need any pagination
and don’t need the count for total number of posts found.
- cache_results (boolean) – Post information cache.
- update_post_meta_cache (boolean) – Post meta information cache.
- update_post_term_cache (boolean) – Post term information cache.
By using these parameters and passing values as FALSE, we can make the query faster by stopping some extra database queries being executed.
Note: We should not use these parameters always as adding things to the cache is the right thing to do, however these may be useful in specific circumstances and you should consider using when you know what you are doing. 🙂
For more information visit: http://codex.wordpress.org/Class_Reference/WP_Query#Caching_Parameters