How to prevent queried posts from being added to cache?

I’m learning about caching parameters and tried this in the single.php template:

echo count($wp_object_cache->cache['posts']);

$query = new \WP_Query([
  'post_type' => 'post',
  'cache_results' => false,
  'posts_per_page' => 5,
  'ignore_sticky_posts' => true
]);

echo '<br>' . count($wp_object_cache->cache['posts']);

The result:

3
7

Somehow, the cache_results parameter didn’t work. Am I missing something?


I’m using:

  • WordPress version 4.6.
  • Twentyfifteen theme.
  • No plugins/third party services.

1 Answer
1

The posts array result in WP_Query is mapped to get_post() (here and here) with:

$this->posts = array_map( 'get_post', $this->posts );

and that seems to be adding posts to the object cache even though the cache_results argument is set to false in WP_Query.

Within the get_post() function (here) we have:

$_post = WP_Post::get_instance( $post );

for the case when $post is neither a WP_Post or an object instance.

The WP_Post::get_instance method contains wp_cache_get() and wp_cache_set() calls.

So that could explain the behavior you see in your example.

Leave a Comment