diff --git a/src/wp-includes/taxonomy-functions.php b/src/wp-includes/taxonomy-functions.php index 8de369c2db..7da100b45f 100644 --- a/src/wp-includes/taxonomy-functions.php +++ b/src/wp-includes/taxonomy-functions.php @@ -4390,8 +4390,10 @@ function is_object_in_term( $object_id, $taxonomy, $terms = null ) { return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) ); $object_terms = get_object_term_cache( $object_id, $taxonomy ); - if ( false === $object_terms ) - $object_terms = wp_get_object_terms( $object_id, $taxonomy, array( 'update_term_meta_cache' => false ) ); + if ( false === $object_terms ) { + $object_terms = wp_get_object_terms( $object_id, $taxonomy, array( 'update_term_meta_cache' => false ) ); + wp_cache_set( $object_id, $object_terms, "{$taxonomy}_relationships" ); + } if ( is_wp_error( $object_terms ) ) return $object_terms; diff --git a/tests/phpunit/tests/term/isObjectInTerm.php b/tests/phpunit/tests/term/isObjectInTerm.php index d6e2940066..be526aee7d 100644 --- a/tests/phpunit/tests/term/isObjectInTerm.php +++ b/tests/phpunit/tests/term/isObjectInTerm.php @@ -100,4 +100,50 @@ class Tests_IsObjectInTerm extends WP_UnitTestCase { wp_set_object_terms( $post_ID, array( $int_tax_name ), 'wptests_tax' ); $this->assertTrue( is_object_in_term( $post_ID, 'wptests_tax', $int_tax_name ) ); } + + /** + * @ticket 32044 + */ + public function test_should_populate_and_hit_relationships_cache() { + global $wpdb; + + register_taxonomy( 'wptests_tax', 'post' ); + $terms = $this->factory->term->create_many( 2, array( 'taxonomy' => 'wptests_tax' ) ); + + $o = 12345; + wp_set_object_terms( $o, $terms[0], 'wptests_tax' ); + + $num_queries = $wpdb->num_queries; + $this->assertTrue( is_object_in_term( $o, 'wptests_tax', $terms[0] ) ); + $num_queries++; + $this->assertSame( $num_queries, $wpdb->num_queries ); + + $this->assertFalse( is_object_in_term( $o, 'wptests_tax', $terms[1] ) ); + $this->assertSame( $num_queries, $wpdb->num_queries ); + } + + /** + * @ticket 32044 + */ + public function test_should_not_be_fooled_by_a_stale_relationship_cache() { + global $wpdb; + + register_taxonomy( 'wptests_tax', 'post' ); + $terms = $this->factory->term->create_many( 2, array( 'taxonomy' => 'wptests_tax' ) ); + + $o = 12345; + wp_set_object_terms( $o, $terms[0], 'wptests_tax' ); + + $num_queries = $wpdb->num_queries; + $this->assertTrue( is_object_in_term( $o, 'wptests_tax', $terms[0] ) ); + $num_queries++; + $this->assertSame( $num_queries, $wpdb->num_queries ); + + wp_set_object_terms( $o, $terms[1], 'wptests_tax' ); + + $num_queries = $wpdb->num_queries; + $this->assertTrue( is_object_in_term( $o, 'wptests_tax', $terms[1] ) ); + $num_queries++; + $this->assertSame( $num_queries, $wpdb->num_queries ); + } }