Here’s some simple code,

$user = get_userdata(5);
print_r($user);
echo $user->first_name;

And the result,

WP_User Object
(
[data] => stdClass Object
    (
        [ID] => 9
        [user_login] => adam@corolla.com
        [user_pass] => $P$Bck6WbL2RpNuUt4VjZGIp525jccfkE/
        [user_nicename] => adamcorolla-com
        [user_email] => adam@corolla.com
        [user_url] => 
        [user_registered] => 2016-04-14 20:35:51
        [user_activation_key] => 
        [user_status] => 0
        [display_name] => addycorolla
    )

[ID] => 9
[caps] => Array
    (
        [subscriber] => 1
    )

[cap_key] => fccv_capabilities
[roles] => Array
    (
        [0] => subscriber
    )

[allcaps] => Array
    (
        [read] => 1
        [level_0] => 1
        [subscriber] => 1
    )

[filter] => 
)

Adam

Why does echo $user->first_name work when the property isn’t listed in the print_r?

1 Answer
1

first_name and last_name are not the part of _users table it is user metadata. Therefore, user object does not have it. So when you access the property first_name user object has a PHP magic method __get()

/**
 * Magic method for accessing custom fields
 *
 * @since 3.3.0
 * @param string $key
 * @return mixed
 */
public function __get( $key ) {
    if ( 'id' == $key ) {
        _deprecated_argument( 'WP_User->id', '2.1', __( 'Use <code>WP_User->ID</code> instead.' ) );
        return $this->ID;
    }

    if ( isset( $this->data->$key ) ) {
        $value = $this->data->$key;
    } else {
        if ( isset( self::$back_compat_keys[ $key ] ) )
            $key = self::$back_compat_keys[ $key ];
        $value = get_user_meta( $this->ID, $key, true );
    }

    if ( $this->filter ) {
        $value = sanitize_user_field( $key, $value, $this->ID, $this->filter );
    }

    return $value;
}

Which query the metadata and return the value from _usermeta table.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *