3 * User API: WP_User class
11 * Core class used to implement the WP_User object.
15 * @property string $nickname
16 * @property string $description
17 * @property string $user_description
18 * @property string $first_name
19 * @property string $user_firstname
20 * @property string $last_name
21 * @property string $user_lastname
22 * @property string $user_login
23 * @property string $user_pass
24 * @property string $user_nicename
25 * @property string $user_email
26 * @property string $user_url
27 * @property string $user_registered
28 * @property string $user_activation_key
29 * @property string $user_status
30 * @property string $display_name
31 * @property string $spam
32 * @property string $deleted
36 * User data container.
53 * The individual capabilities the user has been given.
59 public $caps = array();
62 * User metadata option name.
71 * The roles the user is part of.
77 public $roles = array();
80 * All capabilities the user has, including individual and role based.
86 public $allcaps = array();
89 * The filter context applied to user data fields.
102 private static $back_compat_keys;
107 * Retrieves the userdata and passes it to WP_User::init().
112 * @global wpdb $wpdb WordPress database abstraction object.
114 * @param int|string|stdClass|WP_User $id User's ID, a WP_User object, or a user object from the DB.
115 * @param string $name Optional. User's username
116 * @param int $blog_id Optional Blog ID, defaults to current blog.
118 public function __construct( $id = 0, $name = '', $blog_id = '' ) {
119 if ( ! isset( self::$back_compat_keys ) ) {
120 $prefix = $GLOBALS['wpdb']->prefix;
121 self::$back_compat_keys = array(
122 'user_firstname' => 'first_name',
123 'user_lastname' => 'last_name',
124 'user_description' => 'description',
125 'user_level' => $prefix . 'user_level',
126 $prefix . 'usersettings' => $prefix . 'user-settings',
127 $prefix . 'usersettingstime' => $prefix . 'user-settings-time',
131 if ( $id instanceof WP_User ) {
132 $this->init( $id->data, $blog_id );
134 } elseif ( is_object( $id ) ) {
135 $this->init( $id, $blog_id );
139 if ( ! empty( $id ) && ! is_numeric( $id ) ) {
145 $data = self::get_data_by( 'id', $id );
147 $data = self::get_data_by( 'login', $name );
151 $this->init( $data, $blog_id );
153 $this->data = new stdClass;
158 * Sets up object properties, including capabilities.
160 * @param object $data User DB row object
161 * @param int $blog_id Optional. The blog id to initialize for
163 public function init( $data, $blog_id = '' ) {
165 $this->ID = (int) $data->ID;
167 $this->for_blog( $blog_id );
171 * Return only the main user fields
174 * @since 4.4.0 Added 'ID' as an alias of 'id' for the `$field` parameter.
178 * @global wpdb $wpdb WordPress database abstraction object.
180 * @param string $field The field to query against: 'id', 'ID', 'slug', 'email' or 'login'.
181 * @param string|int $value The field value
182 * @return object|false Raw user object
184 public static function get_data_by( $field, $value ) {
187 // 'ID' is an alias of 'id'.
188 if ( 'ID' === $field ) {
192 if ( 'id' == $field ) {
193 // Make sure the value is numeric to avoid casting objects, for example,
195 if ( ! is_numeric( $value ) )
197 $value = intval( $value );
201 $value = trim( $value );
213 $user_id = wp_cache_get($value, 'userslugs');
214 $db_field = 'user_nicename';
217 $user_id = wp_cache_get($value, 'useremail');
218 $db_field = 'user_email';
221 $value = sanitize_user( $value );
222 $user_id = wp_cache_get($value, 'userlogins');
223 $db_field = 'user_login';
229 if ( false !== $user_id ) {
230 if ( $user = wp_cache_get( $user_id, 'users' ) )
234 if ( !$user = $wpdb->get_row( $wpdb->prepare(
235 "SELECT * FROM $wpdb->users WHERE $db_field = %s", $value
239 update_user_caches( $user );
245 * Makes private/protected methods readable for backwards compatibility.
250 * @param callable $name Method to call.
251 * @param array $arguments Arguments to pass when calling.
252 * @return mixed|false Return value of the callback, false otherwise.
254 public function __call( $name, $arguments ) {
255 if ( '_init_caps' === $name ) {
256 return call_user_func_array( array( $this, $name ), $arguments );
262 * Magic method for checking the existence of a certain custom field.
267 * @param string $key User meta key to check if set.
268 * @return bool Whether the given user meta key is set.
270 public function __isset( $key ) {
271 if ( 'id' == $key ) {
272 _deprecated_argument( 'WP_User->id', '2.1',
274 /* translators: %s: WP_User->ID */
275 __( 'Use %s instead.' ),
276 '<code>WP_User->ID</code>'
282 if ( isset( $this->data->$key ) )
285 if ( isset( self::$back_compat_keys[ $key ] ) )
286 $key = self::$back_compat_keys[ $key ];
288 return metadata_exists( 'user', $this->ID, $key );
292 * Magic method for accessing custom fields.
297 * @param string $key User meta key to retrieve.
298 * @return mixed Value of the given user meta key (if set). If `$key` is 'id', the user ID.
300 public function __get( $key ) {
301 if ( 'id' == $key ) {
302 _deprecated_argument( 'WP_User->id', '2.1',
304 /* translators: %s: WP_User->ID */
305 __( 'Use %s instead.' ),
306 '<code>WP_User->ID</code>'
312 if ( isset( $this->data->$key ) ) {
313 $value = $this->data->$key;
315 if ( isset( self::$back_compat_keys[ $key ] ) )
316 $key = self::$back_compat_keys[ $key ];
317 $value = get_user_meta( $this->ID, $key, true );
320 if ( $this->filter ) {
321 $value = sanitize_user_field( $key, $value, $this->ID, $this->filter );
328 * Magic method for setting custom user fields.
330 * This method does not update custom fields in the database. It only stores
331 * the value on the WP_User instance.
336 * @param string $key User meta key.
337 * @param mixed $value User meta value.
339 public function __set( $key, $value ) {
340 if ( 'id' == $key ) {
341 _deprecated_argument( 'WP_User->id', '2.1',
343 /* translators: %s: WP_User->ID */
344 __( 'Use %s instead.' ),
345 '<code>WP_User->ID</code>'
352 $this->data->$key = $value;
356 * Magic method for unsetting a certain custom field.
361 * @param string $key User meta key to unset.
363 public function __unset( $key ) {
364 if ( 'id' == $key ) {
365 _deprecated_argument( 'WP_User->id', '2.1',
367 /* translators: %s: WP_User->ID */
368 __( 'Use %s instead.' ),
369 '<code>WP_User->ID</code>'
374 if ( isset( $this->data->$key ) ) {
375 unset( $this->data->$key );
378 if ( isset( self::$back_compat_keys[ $key ] ) ) {
379 unset( self::$back_compat_keys[ $key ] );
384 * Determine whether the user exists in the database.
389 * @return bool True if user exists in the database, false if not.
391 public function exists() {
392 return ! empty( $this->ID );
396 * Retrieve the value of a property or meta key.
398 * Retrieves from the users and usermeta table.
402 * @param string $key Property
405 public function get( $key ) {
406 return $this->__get( $key );
410 * Determine whether a property or meta key is set
412 * Consults the users and usermeta tables.
416 * @param string $key Property
419 public function has_prop( $key ) {
420 return $this->__isset( $key );
424 * Return an array representation.
428 * @return array Array representation.
430 public function to_array() {
431 return get_object_vars( $this->data );
435 * Set up capability object properties.
437 * Will set the value for the 'cap_key' property to current database table
438 * prefix, followed by 'capabilities'. Will then check to see if the
439 * property matching the 'cap_key' exists and is an array. If so, it will be
445 * @global wpdb $wpdb WordPress database abstraction object.
447 * @param string $cap_key Optional capability key
449 protected function _init_caps( $cap_key = '' ) {
452 if ( empty($cap_key) )
453 $this->cap_key = $wpdb->get_blog_prefix() . 'capabilities';
455 $this->cap_key = $cap_key;
457 $this->caps = get_user_meta( $this->ID, $this->cap_key, true );
459 if ( ! is_array( $this->caps ) )
460 $this->caps = array();
462 $this->get_role_caps();
466 * Retrieve all of the role capabilities and merge with individual capabilities.
468 * All of the capabilities of the roles the user belongs to are merged with
469 * the users individual roles. This also means that the user can be denied
470 * specific roles that their role might have, but the specific user isn't
471 * granted permission to.
476 * @return array List of all capabilities for the user.
478 public function get_role_caps() {
479 $wp_roles = wp_roles();
481 //Filter out caps that are not role names and assign to $this->roles
482 if ( is_array( $this->caps ) )
483 $this->roles = array_filter( array_keys( $this->caps ), array( $wp_roles, 'is_role' ) );
485 //Build $allcaps from role caps, overlay user's $caps
486 $this->allcaps = array();
487 foreach ( (array) $this->roles as $role ) {
488 $the_role = $wp_roles->get_role( $role );
489 $this->allcaps = array_merge( (array) $this->allcaps, (array) $the_role->capabilities );
491 $this->allcaps = array_merge( (array) $this->allcaps, (array) $this->caps );
493 return $this->allcaps;
499 * Updates the user's meta data option with capabilities and roles.
504 * @param string $role Role name.
506 public function add_role( $role ) {
507 if ( empty( $role ) ) {
511 $this->caps[$role] = true;
512 update_user_meta( $this->ID, $this->cap_key, $this->caps );
513 $this->get_role_caps();
514 $this->update_user_level_from_caps();
517 * Fires immediately after the user has been given a new role.
521 * @param int $user_id The user ID.
522 * @param string $role The new role.
524 do_action( 'add_user_role', $this->ID, $role );
528 * Remove role from user.
533 * @param string $role Role name.
535 public function remove_role( $role ) {
536 if ( !in_array($role, $this->roles) )
538 unset( $this->caps[$role] );
539 update_user_meta( $this->ID, $this->cap_key, $this->caps );
540 $this->get_role_caps();
541 $this->update_user_level_from_caps();
544 * Fires immediately after a role as been removed from a user.
548 * @param int $user_id The user ID.
549 * @param string $role The removed role.
551 do_action( 'remove_user_role', $this->ID, $role );
555 * Set the role of the user.
557 * This will remove the previous roles of the user and assign the user the
558 * new one. You can set the role to an empty string and it will remove all
559 * of the roles from the user.
564 * @param string $role Role name.
566 public function set_role( $role ) {
567 if ( 1 == count( $this->roles ) && $role == current( $this->roles ) )
570 foreach ( (array) $this->roles as $oldrole )
571 unset( $this->caps[$oldrole] );
573 $old_roles = $this->roles;
574 if ( !empty( $role ) ) {
575 $this->caps[$role] = true;
576 $this->roles = array( $role => true );
578 $this->roles = false;
580 update_user_meta( $this->ID, $this->cap_key, $this->caps );
581 $this->get_role_caps();
582 $this->update_user_level_from_caps();
585 * Fires after the user's role has changed.
588 * @since 3.6.0 Added $old_roles to include an array of the user's previous roles.
590 * @param int $user_id The user ID.
591 * @param string $role The new role.
592 * @param array $old_roles An array of the user's previous roles.
594 do_action( 'set_user_role', $this->ID, $role, $old_roles );
598 * Choose the maximum level the user has.
600 * Will compare the level from the $item parameter against the $max
601 * parameter. If the item is incorrect, then just the $max parameter value
604 * Used to get the max level based on the capabilities the user has. This
605 * is also based on roles, so if the user is assigned the Administrator role
606 * then the capability 'level_10' will exist and the user will get that
612 * @param int $max Max level of user.
613 * @param string $item Level capability name.
614 * @return int Max Level.
616 public function level_reduction( $max, $item ) {
617 if ( preg_match( '/^level_(10|[0-9])$/i', $item, $matches ) ) {
618 $level = intval( $matches[1] );
619 return max( $max, $level );
626 * Update the maximum user level for the user.
628 * Updates the 'user_level' user metadata (includes prefix that is the
629 * database table prefix) with the maximum user level. Gets the value from
630 * the all of the capabilities that the user has.
635 * @global wpdb $wpdb WordPress database abstraction object.
637 public function update_user_level_from_caps() {
639 $this->user_level = array_reduce( array_keys( $this->allcaps ), array( $this, 'level_reduction' ), 0 );
640 update_user_meta( $this->ID, $wpdb->get_blog_prefix() . 'user_level', $this->user_level );
644 * Add capability and grant or deny access to capability.
649 * @param string $cap Capability name.
650 * @param bool $grant Whether to grant capability to user.
652 public function add_cap( $cap, $grant = true ) {
653 $this->caps[$cap] = $grant;
654 update_user_meta( $this->ID, $this->cap_key, $this->caps );
655 $this->get_role_caps();
656 $this->update_user_level_from_caps();
660 * Remove capability from user.
665 * @param string $cap Capability name.
667 public function remove_cap( $cap ) {
668 if ( ! isset( $this->caps[ $cap ] ) ) {
671 unset( $this->caps[ $cap ] );
672 update_user_meta( $this->ID, $this->cap_key, $this->caps );
673 $this->get_role_caps();
674 $this->update_user_level_from_caps();
678 * Remove all of the capabilities of the user.
683 * @global wpdb $wpdb WordPress database abstraction object.
685 public function remove_all_caps() {
687 $this->caps = array();
688 delete_user_meta( $this->ID, $this->cap_key );
689 delete_user_meta( $this->ID, $wpdb->get_blog_prefix() . 'user_level' );
690 $this->get_role_caps();
694 * Whether user has capability or role name.
696 * While checking against particular roles in place of a capability is supported
697 * in part, this practice is discouraged as it may produce unreliable results.
702 * @see map_meta_cap()
704 * @param string $cap Capability name.
705 * @param int $object_id Optional. ID of the specific object to check against if `$cap` is a "meta" cap.
706 * "Meta" capabilities, e.g. 'edit_post', 'edit_user', etc., are capabilities used
707 * by map_meta_cap() to map to other "primitive" capabilities, e.g. 'edit_posts',
708 * 'edit_others_posts', etc. The parameter is accessed via func_get_args() and passed
710 * @return bool Whether the current user has the given capability. If `$cap` is a meta cap and `$object_id` is
711 * passed, whether the current user has the given meta capability for the given object.
713 public function has_cap( $cap ) {
714 if ( is_numeric( $cap ) ) {
715 _deprecated_argument( __FUNCTION__, '2.0', __('Usage of user levels by plugins and themes is deprecated. Use roles and capabilities instead.') );
716 $cap = $this->translate_level_to_cap( $cap );
719 $args = array_slice( func_get_args(), 1 );
720 $args = array_merge( array( $cap, $this->ID ), $args );
721 $caps = call_user_func_array( 'map_meta_cap', $args );
723 // Multisite super admin has all caps by definition, Unless specifically denied.
724 if ( is_multisite() && is_super_admin( $this->ID ) ) {
725 if ( in_array('do_not_allow', $caps) )
731 * Dynamically filter a user's capabilities.
734 * @since 3.7.0 Added the user object.
736 * @param array $allcaps An array of all the user's capabilities.
737 * @param array $caps Actual capabilities for meta capability.
738 * @param array $args Optional parameters passed to has_cap(), typically object ID.
739 * @param WP_User $user The user object.
741 $capabilities = apply_filters( 'user_has_cap', $this->allcaps, $caps, $args, $this );
743 // Everyone is allowed to exist.
744 $capabilities['exist'] = true;
746 // Must have ALL requested caps.
747 foreach ( (array) $caps as $cap ) {
748 if ( empty( $capabilities[ $cap ] ) )
756 * Convert numeric level to level capability name.
758 * Prepends 'level_' to level number.
763 * @param int $level Level number, 1 to 10.
766 public function translate_level_to_cap( $level ) {
767 return 'level_' . $level;
771 * Set the blog to operate on. Defaults to the current blog.
775 * @global wpdb $wpdb WordPress database abstraction object.
777 * @param int $blog_id Optional Blog ID, defaults to current blog.
779 public function for_blog( $blog_id = '' ) {
781 if ( ! empty( $blog_id ) )
782 $cap_key = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
785 $this->_init_caps( $cap_key );