Don’t Cache WP_Query Objects
Slow website? Run our WordPress performance and security benchmark to find out! WP_Query is one of the most complex classes in the WordPress codebase. It’s extremely powerful and flexible, but that flexibility often results in slower database queries, especially when working with metadata. To speed things up, WordPress developers tend to cache the results of such queries, but there are a few pitfalls you should be aware of.
Caching Queries
The Transients API is likely the top choice for caching WP_Query results, but what we often see is developers storing the whole WP_Query object in a transient, and we believe that’s a mistake. Translating that into code, it looks something like this:
$cache_key = ‘my-expensive-query’;
if ( ! $cache_key = get_transient( $cache_key ) ) {
$query = new WP_Query( … ); // some expensive query;
set_transient( $cache_key, $query, 24 * HOUR_IN_SECONDS );
}
while ( $query->have_posts() ) {
$query->the_post();
// …
}
Here you can see that we’re passing the $query object directly to set_transient(), so whenever we get a cache hit, we’ll have our query object available, along with all the useful WP_Query properties
Source: https://managewp.org/articles/13835/don-t-cache-wp-query-objects
source https://williechiu40.wordpress.com/2016/11/15/dont-cache-wp_query-objects/