diff --git a/src/wp-includes/pluggable.php b/src/wp-includes/pluggable.php index d58f18940b..98403b34ae 100644 --- a/src/wp-includes/pluggable.php +++ b/src/wp-includes/pluggable.php @@ -26,8 +26,14 @@ if ( !function_exists('wp_set_current_user') ) : function wp_set_current_user($id, $name = '') { global $current_user; - if ( isset( $current_user ) && ( $current_user instanceof WP_User ) && ( $id == $current_user->ID ) ) + // If `$id` matches the user who's already current, there's nothing to do. + if ( isset( $current_user ) + && ( $current_user instanceof WP_User ) + && ( $id == $current_user->ID ) + && ( null !== $id ) + ) { return $current_user; + } $current_user = new WP_User( $id, $name ); diff --git a/tests/phpunit/tests/user/wpSetCurrentUser.php b/tests/phpunit/tests/user/wpSetCurrentUser.php index c47c22cc74..b3c8fce918 100644 --- a/tests/phpunit/tests/user/wpSetCurrentUser.php +++ b/tests/phpunit/tests/user/wpSetCurrentUser.php @@ -23,5 +23,41 @@ class Tests_User_WpSetCurrentUser extends WP_UnitTestCase { $this->assertEquals( $user, wp_get_current_user() ); $this->assertSame( $u, get_current_user_id() ); } + + public function test_should_set_by_name_if_id_is_null_and_current_user_is_nonempty() { + $u1 = $this->factory->user->create(); + wp_set_current_user( $u1 ); + $this->assertSame( $u1, get_current_user_id() ); + + $u2 = $this->factory->user->create( array( + 'user_login' => 'foo', + ) ); + + $user = wp_set_current_user( null, 'foo' ); + + $this->assertSame( $u2, $user->ID ); + $this->assertEquals( $user, wp_get_current_user() ); + $this->assertSame( $u2, get_current_user_id() ); + } + + /** + * Test that you can set the current user by the name parameter when the current user is 0. + * + * @ticket 20845 + */ + public function test_should_set_by_name_if_id_is_null() { + wp_set_current_user( 0 ); + $this->assertSame( 0, get_current_user_id() ); + + $u = $this->factory->user->create( array( + 'user_login' => 'foo', + ) ); + + $user = wp_set_current_user( null, 'foo' ); + + $this->assertSame( $u, $user->ID ); + $this->assertEquals( $user, wp_get_current_user() ); + $this->assertSame( $u, get_current_user_id() ); + } }