diff --git a/src/wp-includes/class-wp-query.php b/src/wp-includes/class-wp-query.php index 4b17618907..7af38f135b 100644 --- a/src/wp-includes/class-wp-query.php +++ b/src/wp-includes/class-wp-query.php @@ -3099,10 +3099,10 @@ class WP_Query { $last_changed .= wp_cache_get_last_changed( 'terms' ); } - $cache_key = "wp_query:$key:$last_changed"; - + $cache_key = "wp_query:$key:$last_changed"; + $cache_found = false; if ( null === $this->posts ) { - $cached_results = wp_cache_get( $cache_key, 'posts' ); + $cached_results = wp_cache_get( $cache_key, 'posts', false, $cache_found ); if ( $cached_results ) { if ( 'ids' === $q['fields'] ) { @@ -3256,7 +3256,7 @@ class WP_Query { $this->posts = array_map( 'get_post', $this->posts ); } - if ( $q['cache_results'] && $id_query_is_cacheable ) { + if ( $q['cache_results'] && $id_query_is_cacheable && ! $cache_found ) { $post_ids = wp_list_pluck( $this->posts, 'ID' ); $cache_value = array( @@ -3455,7 +3455,8 @@ class WP_Query { $this->posts = array_map( 'get_post', $this->posts ); if ( $q['cache_results'] ) { - update_post_caches( $this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache'] ); + $post_ids = wp_list_pluck( $this->posts, 'ID' ); + _prime_post_caches( $post_ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] ); } /** @var WP_Post */ diff --git a/tests/phpunit/tests/query/cacheResults.php b/tests/phpunit/tests/query/cacheResults.php index d93b5ae9f1..723c78a2bf 100644 --- a/tests/phpunit/tests/query/cacheResults.php +++ b/tests/phpunit/tests/query/cacheResults.php @@ -984,4 +984,46 @@ class Test_Query_CacheResults extends WP_UnitTestCase { $this->assertContains( $post_id, $post_ids_q2, 'Second query does not include the post ID.' ); $this->assertNotSame( $num_queries, get_num_queries(), 'Removing term does not invalidate previous cache.' ); } + + /** + * @ticket 22176 + * @dataProvider data_query_cache_with_empty_result_set + */ + public function test_query_cache_with_empty_result_set( $fields_q1, $fields_q2 ) { + _delete_all_posts(); + + $args_q1 = array( + 'fields' => $fields_q1, + ); + + $query_1 = new WP_Query(); + $posts_q1 = $query_1->query( $args_q1 ); + $this->assertEmpty( $posts_q1, 'First query does not return an empty result set.' ); + + $args_q2 = array( + 'fields' => $fields_q2, + ); + + $num_queries = get_num_queries(); + $query_2 = new WP_Query(); + $posts_q2 = $query_2->query( $args_q2 ); + $this->assertEmpty( $posts_q2, 'Second query does not return an empty result set.' ); + $this->assertSame( $num_queries, get_num_queries(), 'Second query is not cached.' ); + } + + public function data_query_cache_with_empty_result_set() { + return array( + array( '', '' ), + array( '', 'ids' ), + array( '', 'id=>parent' ), + + array( 'ids', '' ), + array( 'ids', 'ids' ), + array( 'ids', 'id=>parent' ), + + array( 'id=>parent', '' ), + array( 'id=>parent', 'ids' ), + array( 'id=>parent', 'id=>parent' ), + ); + } }