diff --git a/src/wp-includes/ms-site.php b/src/wp-includes/ms-site.php index 6399dab72e881..6b35a093476d6 100644 --- a/src/wp-includes/ms-site.php +++ b/src/wp-includes/ms-site.php @@ -701,6 +701,7 @@ function wp_initialize_site( $site_id, array $args = array() ) { $switch = false; if ( get_current_blog_id() !== $site->id ) { $switch = true; + remove_action( 'switch_blog', 'wp_switch_roles_and_user', 1 ); switch_to_blog( $site->id ); } @@ -740,8 +741,8 @@ function wp_initialize_site( $site_id, array $args = array() ) { clean_blog_cache( $site ); // Populate the site's roles. - populate_roles(); $wp_roles = new WP_Roles(); + populate_roles(); // Populate metadata for the site. populate_site_meta( $site->id, $args['meta'] ); @@ -761,6 +762,7 @@ function wp_initialize_site( $site_id, array $args = array() ) { } if ( $switch ) { + add_action( 'switch_blog', 'wp_switch_roles_and_user', 1, 2 ); restore_current_blog(); } diff --git a/tests/phpunit/tests/multisite/site.php b/tests/phpunit/tests/multisite/site.php index 920a76f6a7e30..cc30e5f8a6506 100644 --- a/tests/phpunit/tests/multisite/site.php +++ b/tests/phpunit/tests/multisite/site.php @@ -1996,6 +1996,43 @@ public function test_wp_initialize_site_user_roles() { ); } + /** + * @ticket 37685 + */ + public function test_wp_initialize_site_does_not_query_user_roles_before_tables_exist() { + global $EZSQL_ERROR; + + $error_count_before = count( (array) $EZSQL_ERROR ); + + $result = wp_initialize_site( self::$uninitialized_site_id, array() ); + + $new_errors = array_slice( (array) $EZSQL_ERROR, $error_count_before ); + + wp_uninitialize_site( self::$uninitialized_site_id ); + + $this->assertTrue( $result ); + + foreach ( $new_errors as $error ) { + $this->assertStringNotContainsString( 'user_roles', $error['query'] ); + } + } + + /** + * @ticket 37685 + */ + public function test_wp_initialize_site_restores_global_state() { + $blog_id_before = get_current_blog_id(); + $roles_site_id_before = wp_roles()->get_site_id(); + + $result = wp_initialize_site( self::$uninitialized_site_id, array() ); + + wp_uninitialize_site( self::$uninitialized_site_id ); + + $this->assertTrue( $result ); + $this->assertSame( $blog_id_before, get_current_blog_id() ); + $this->assertSame( $roles_site_id_before, wp_roles()->get_site_id() ); + } + /** * @ticket 41333 */