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 ) );