WordPress.org

Make WordPress Core

Changeset 34947


Ignore:
Timestamp:
10/08/2015 05:28:34 PM (4 years ago)
Author:
boonebgorges
Message:

Allow a null id to do a name lookup in wp_set_current_user().

Previously, the name fallback was failing in the case where the current user
was 0, due to a loose comparison between 0 (the current user) and null (the
value that is used to trigger the name fallback).

Props bobbingwide.
Fixes #20845.

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/pluggable.php

    r34924 r34947  
    2727    global $current_user;
    2828
    29     if ( isset( $current_user ) && ( $current_user instanceof WP_User ) && ( $id == $current_user->ID ) )
     29    // If `$id` matches the user who's already current, there's nothing to do.
     30    if ( isset( $current_user )
     31        && ( $current_user instanceof WP_User )
     32        && ( $id == $current_user->ID )
     33        && ( null !== $id )
     34    ) {
    3035        return $current_user;
     36    }
    3137
    3238    $current_user = new WP_User( $id, $name );
  • trunk/tests/phpunit/tests/user/wpSetCurrentUser.php

    r34945 r34947  
    2424        $this->assertSame( $u, get_current_user_id() );
    2525    }
     26
     27    public function test_should_set_by_name_if_id_is_null_and_current_user_is_nonempty() {
     28        $u1 = $this->factory->user->create();
     29        wp_set_current_user( $u1 );
     30        $this->assertSame( $u1, get_current_user_id() );
     31
     32        $u2 = $this->factory->user->create( array(
     33            'user_login' => 'foo',
     34        ) );
     35
     36        $user = wp_set_current_user( null, 'foo' );
     37
     38        $this->assertSame( $u2, $user->ID );
     39        $this->assertEquals( $user, wp_get_current_user() );
     40        $this->assertSame( $u2, get_current_user_id() );
     41    }
     42
     43    /**
     44     * Test that you can set the current user by the name parameter when the current user is 0.
     45     *
     46     * @ticket 20845
     47     */
     48    public function test_should_set_by_name_if_id_is_null() {
     49        wp_set_current_user( 0 );
     50        $this->assertSame( 0, get_current_user_id() );
     51
     52        $u = $this->factory->user->create( array(
     53            'user_login' => 'foo',
     54        ) );
     55
     56        $user = wp_set_current_user( null, 'foo' );
     57
     58        $this->assertSame( $u, $user->ID );
     59        $this->assertEquals( $user, wp_get_current_user() );
     60        $this->assertSame( $u, get_current_user_id() );
     61    }
    2662}
    2763
Note: See TracChangeset for help on using the changeset viewer.