diff --git a/src/wp-includes/class-wp-term-query.php b/src/wp-includes/class-wp-term-query.php index cae93a920d..f0df73f906 100644 --- a/src/wp-includes/class-wp-term-query.php +++ b/src/wp-includes/class-wp-term-query.php @@ -690,7 +690,9 @@ class WP_Term_Query { } if ( 'count' == $_fields ) { - return $wpdb->get_var( $this->request ); + $count = $wpdb->get_var( $this->request ); + wp_cache_set( $cache_key, $count, 'terms' ); + return $count; } $terms = $wpdb->get_results( $this->request ); diff --git a/tests/phpunit/tests/term/query.php b/tests/phpunit/tests/term/query.php index da60cad32d..4a15f1e53f 100644 --- a/tests/phpunit/tests/term/query.php +++ b/tests/phpunit/tests/term/query.php @@ -322,4 +322,63 @@ class Tests_Term_Query extends WP_UnitTestCase { $this->assertEqualSets( array( $terms[1] ), $found ); } + + /** + * @ticket 38295 + * @group cache + */ + public function test_count_query_should_be_cached() { + global $wpdb; + + register_taxonomy( 'wptests_tax_1', 'post' ); + + $terms = self::factory()->term->create_many( 2, array( 'taxonomy' => 'wptests_tax_1' ) ); + + $query = new WP_Term_Query( array( + 'taxonomy' => 'wptests_tax_1', + 'fields' => 'count', + 'hide_empty' => false, + ) ); + $count = $query->get_terms(); + $this->assertEquals( 2, $count ); + + $num_queries = $wpdb->num_queries; + + $query = new WP_Term_Query( array( + 'taxonomy' => 'wptests_tax_1', + 'fields' => 'count', + 'hide_empty' => false, + ) ); + $count = $query->get_terms(); + $this->assertEquals( 2, $count ); + $this->assertSame( $num_queries, $wpdb->num_queries ); + } + + /** + * @ticket 38295 + * @group cache + */ + public function test_count_query_cache_should_be_invalidated_with_incrementor_bump() { + register_taxonomy( 'wptests_tax_1', 'post' ); + + $terms = self::factory()->term->create_many( 2, array( 'taxonomy' => 'wptests_tax_1' ) ); + + $query = new WP_Term_Query( array( + 'taxonomy' => 'wptests_tax_1', + 'fields' => 'count', + 'hide_empty' => false, + ) ); + $count = $query->get_terms(); + $this->assertEquals( 2, $count ); + + wp_delete_term( $terms[0], 'wptests_tax_1' ); + + $query = new WP_Term_Query( array( + 'taxonomy' => 'wptests_tax_1', + 'fields' => 'count', + 'hide_empty' => false, + ) ); + $count = $query->get_terms(); + $this->assertEquals( 1, $count ); + } }