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 int $user_level
31 * @property string $display_name
32 * @property string $spam
33 * @property string $deleted
34 * @property string $locale
38 * User data container.
55 * The individual capabilities the user has been given.
61 public $caps = array();
64 * User metadata option name.
73 * The roles the user is part of.
79 public $roles = array();
82 * All capabilities the user has, including individual and role based.
88 public $allcaps = array();
91 * The filter context applied to user data fields.
104 private static $back_compat_keys;
109 * Retrieves the userdata and passes it to WP_User::init().
114 * @global wpdb $wpdb WordPress database abstraction object.
116 * @param int|string|stdClass|WP_User $id User's ID, a WP_User object, or a user object from the DB.
117 * @param string $name Optional. User's username
118 * @param int $blog_id Optional Site ID, defaults to current site.
120 public function __construct( $id = 0, $name = '', $blog_id = '' ) {
121 if ( ! isset( self::$back_compat_keys ) ) {
122 $prefix = $GLOBALS['wpdb']->prefix;
123 self::$back_compat_keys = array(
124 'user_firstname' => 'first_name',
125 'user_lastname' => 'last_name',
126 'user_description' => 'description',
127 'user_level' => $prefix . 'user_level',
128 $prefix . 'usersettings' => $prefix . 'user-settings',
129 $prefix . 'usersettingstime' => $prefix . 'user-settings-time',
133 if ( $id instanceof WP_User ) {
134 $this->init( $id->data, $blog_id );
136 } elseif ( is_object( $id ) ) {
137 $this->init( $id, $blog_id );
141 if ( ! empty( $id ) && ! is_numeric( $id ) ) {
147 $data = self::get_data_by( 'id', $id );
149 $data = self::get_data_by( 'login', $name );
153 $this->init( $data, $blog_id );
155 $this->data = new stdClass;
160 * Sets up object properties, including capabilities.
162 * @param object $data User DB row object.
163 * @param int $blog_id Optional. The site ID to initialize for.
165 public function init( $data, $blog_id = '' ) {
167 $this->ID = (int) $data->ID;
169 $this->for_blog( $blog_id );
173 * Return only the main user fields
176 * @since 4.4.0 Added 'ID' as an alias of 'id' for the `$field` parameter.
180 * @global wpdb $wpdb WordPress database abstraction object.
182 * @param string $field The field to query against: 'id', 'ID', 'slug', 'email' or 'login'.
183 * @param string|int $value The field value
184 * @return object|false Raw user object
186 public static function get_data_by( $field, $value ) {
189 // 'ID' is an alias of 'id'.
190 if ( 'ID' === $field ) {
194 if ( 'id' == $field ) {
195 // Make sure the value is numeric to avoid casting objects, for example,
197 if ( ! is_numeric( $value ) )
199 $value = intval( $value );
203 $value = trim( $value );
215 $user_id = wp_cache_get($value, 'userslugs');
216 $db_field = 'user_nicename';
219 $user_id = wp_cache_get($value, 'useremail');
220 $db_field = 'user_email';
223 $value = sanitize_user( $value );
224 $user_id = wp_cache_get($value, 'userlogins');
225 $db_field = 'user_login';
231 if ( false !== $user_id ) {
232 if ( $user = wp_cache_get( $user_id, 'users' ) )
236 if ( !$user = $wpdb->get_row( $wpdb->prepare(
237 "SELECT * FROM $wpdb->users WHERE $db_field = %s", $value
241 update_user_caches( $user );
247 * Makes private/protected methods readable for backward compatibility.
252 * @param callable $name Method to call.
253 * @param array $arguments Arguments to pass when calling.
254 * @return mixed|false Return value of the callback, false otherwise.
256 public function __call( $name, $arguments ) {
257 if ( '_init_caps' === $name ) {
258 return call_user_func_array( array( $this, $name ), $arguments );
264 * Magic method for checking the existence of a certain custom field.
269 * @param string $key User meta key to check if set.
270 * @return bool Whether the given user meta key is set.
272 public function __isset( $key ) {
273 if ( 'id' == $key ) {
274 _deprecated_argument( 'WP_User->id', '2.1.0',
276 /* translators: %s: WP_User->ID */
277 __( 'Use %s instead.' ),
278 '<code>WP_User->ID</code>'
284 if ( isset( $this->data->$key ) )
287 if ( isset( self::$back_compat_keys[ $key ] ) )
288 $key = self::$back_compat_keys[ $key ];
290 return metadata_exists( 'user', $this->ID, $key );
294 * Magic method for accessing custom fields.
299 * @param string $key User meta key to retrieve.
300 * @return mixed Value of the given user meta key (if set). If `$key` is 'id', the user ID.
302 public function __get( $key ) {
303 if ( 'id' == $key ) {
304 _deprecated_argument( 'WP_User->id', '2.1.0',
306 /* translators: %s: WP_User->ID */
307 __( 'Use %s instead.' ),
308 '<code>WP_User->ID</code>'
314 if ( isset( $this->data->$key ) ) {
315 $value = $this->data->$key;
317 if ( isset( self::$back_compat_keys[ $key ] ) )
318 $key = self::$back_compat_keys[ $key ];
319 $value = get_user_meta( $this->ID, $key, true );
322 if ( $this->filter ) {
323 $value = sanitize_user_field( $key, $value, $this->ID, $this->filter );
330 * Magic method for setting custom user fields.
332 * This method does not update custom fields in the database. It only stores
333 * the value on the WP_User instance.
338 * @param string $key User meta key.
339 * @param mixed $value User meta value.
341 public function __set( $key, $value ) {
342 if ( 'id' == $key ) {
343 _deprecated_argument( 'WP_User->id', '2.1.0',
345 /* translators: %s: WP_User->ID */
346 __( 'Use %s instead.' ),
347 '<code>WP_User->ID</code>'
354 $this->data->$key = $value;
358 * Magic method for unsetting a certain custom field.
363 * @param string $key User meta key to unset.
365 public function __unset( $key ) {
366 if ( 'id' == $key ) {
367 _deprecated_argument( 'WP_User->id', '2.1.0',
369 /* translators: %s: WP_User->ID */
370 __( 'Use %s instead.' ),
371 '<code>WP_User->ID</code>'
376 if ( isset( $this->data->$key ) ) {
377 unset( $this->data->$key );
380 if ( isset( self::$back_compat_keys[ $key ] ) ) {
381 unset( self::$back_compat_keys[ $key ] );
386 * Determine whether the user exists in the database.
391 * @return bool True if user exists in the database, false if not.
393 public function exists() {
394 return ! empty( $this->ID );
398 * Retrieve the value of a property or meta key.
400 * Retrieves from the users and usermeta table.
404 * @param string $key Property
407 public function get( $key ) {
408 return $this->__get( $key );
412 * Determine whether a property or meta key is set
414 * Consults the users and usermeta tables.
418 * @param string $key Property
421 public function has_prop( $key ) {
422 return $this->__isset( $key );
426 * Return an array representation.
430 * @return array Array representation.
432 public function to_array() {
433 return get_object_vars( $this->data );
437 * Set up capability object properties.
439 * Will set the value for the 'cap_key' property to current database table
440 * prefix, followed by 'capabilities'. Will then check to see if the
441 * property matching the 'cap_key' exists and is an array. If so, it will be
447 * @global wpdb $wpdb WordPress database abstraction object.
449 * @param string $cap_key Optional capability key
451 protected function _init_caps( $cap_key = '' ) {
454 if ( empty($cap_key) )
455 $this->cap_key = $wpdb->get_blog_prefix() . 'capabilities';
457 $this->cap_key = $cap_key;
459 $this->caps = get_user_meta( $this->ID, $this->cap_key, true );
461 if ( ! is_array( $this->caps ) )
462 $this->caps = array();
464 $this->get_role_caps();
468 * Retrieve all of the role capabilities and merge with individual capabilities.
470 * All of the capabilities of the roles the user belongs to are merged with
471 * the users individual roles. This also means that the user can be denied
472 * specific roles that their role might have, but the specific user isn't
473 * granted permission to.
478 * @return array List of all capabilities for the user.
480 public function get_role_caps() {
481 $wp_roles = wp_roles();
483 //Filter out caps that are not role names and assign to $this->roles
484 if ( is_array( $this->caps ) )
485 $this->roles = array_filter( array_keys( $this->caps ), array( $wp_roles, 'is_role' ) );
487 //Build $allcaps from role caps, overlay user's $caps
488 $this->allcaps = array();
489 foreach ( (array) $this->roles as $role ) {
490 $the_role = $wp_roles->get_role( $role );
491 $this->allcaps = array_merge( (array) $this->allcaps, (array) $the_role->capabilities );
493 $this->allcaps = array_merge( (array) $this->allcaps, (array) $this->caps );
495 return $this->allcaps;
501 * Updates the user's meta data option with capabilities and roles.
506 * @param string $role Role name.
508 public function add_role( $role ) {
509 if ( empty( $role ) ) {
513 $this->caps[$role] = true;
514 update_user_meta( $this->ID, $this->cap_key, $this->caps );
515 $this->get_role_caps();
516 $this->update_user_level_from_caps();
519 * Fires immediately after the user has been given a new role.
523 * @param int $user_id The user ID.
524 * @param string $role The new role.
526 do_action( 'add_user_role', $this->ID, $role );
530 * Remove role from user.
535 * @param string $role Role name.
537 public function remove_role( $role ) {
538 if ( !in_array($role, $this->roles) )
540 unset( $this->caps[$role] );
541 update_user_meta( $this->ID, $this->cap_key, $this->caps );
542 $this->get_role_caps();
543 $this->update_user_level_from_caps();
546 * Fires immediately after a role as been removed from a user.
550 * @param int $user_id The user ID.
551 * @param string $role The removed role.
553 do_action( 'remove_user_role', $this->ID, $role );
557 * Set the role of the user.
559 * This will remove the previous roles of the user and assign the user the
560 * new one. You can set the role to an empty string and it will remove all
561 * of the roles from the user.
566 * @param string $role Role name.
568 public function set_role( $role ) {
569 if ( 1 == count( $this->roles ) && $role == current( $this->roles ) )
572 foreach ( (array) $this->roles as $oldrole )
573 unset( $this->caps[$oldrole] );
575 $old_roles = $this->roles;
576 if ( !empty( $role ) ) {
577 $this->caps[$role] = true;
578 $this->roles = array( $role => true );
580 $this->roles = false;
582 update_user_meta( $this->ID, $this->cap_key, $this->caps );
583 $this->get_role_caps();
584 $this->update_user_level_from_caps();
587 * Fires after the user's role has changed.
590 * @since 3.6.0 Added $old_roles to include an array of the user's previous roles.
592 * @param int $user_id The user ID.
593 * @param string $role The new role.
594 * @param array $old_roles An array of the user's previous roles.
596 do_action( 'set_user_role', $this->ID, $role, $old_roles );
600 * Choose the maximum level the user has.
602 * Will compare the level from the $item parameter against the $max
603 * parameter. If the item is incorrect, then just the $max parameter value
606 * Used to get the max level based on the capabilities the user has. This
607 * is also based on roles, so if the user is assigned the Administrator role
608 * then the capability 'level_10' will exist and the user will get that
614 * @param int $max Max level of user.
615 * @param string $item Level capability name.
616 * @return int Max Level.
618 public function level_reduction( $max, $item ) {
619 if ( preg_match( '/^level_(10|[0-9])$/i', $item, $matches ) ) {
620 $level = intval( $matches[1] );
621 return max( $max, $level );
628 * Update the maximum user level for the user.
630 * Updates the 'user_level' user metadata (includes prefix that is the
631 * database table prefix) with the maximum user level. Gets the value from
632 * the all of the capabilities that the user has.
637 * @global wpdb $wpdb WordPress database abstraction object.
639 public function update_user_level_from_caps() {
641 $this->user_level = array_reduce( array_keys( $this->allcaps ), array( $this, 'level_reduction' ), 0 );
642 update_user_meta( $this->ID, $wpdb->get_blog_prefix() . 'user_level', $this->user_level );
646 * Add capability and grant or deny access to capability.
651 * @param string $cap Capability name.
652 * @param bool $grant Whether to grant capability to user.
654 public function add_cap( $cap, $grant = true ) {
655 $this->caps[$cap] = $grant;
656 update_user_meta( $this->ID, $this->cap_key, $this->caps );
657 $this->get_role_caps();
658 $this->update_user_level_from_caps();
662 * Remove capability from user.
667 * @param string $cap Capability name.
669 public function remove_cap( $cap ) {
670 if ( ! isset( $this->caps[ $cap ] ) ) {
673 unset( $this->caps[ $cap ] );
674 update_user_meta( $this->ID, $this->cap_key, $this->caps );
675 $this->get_role_caps();
676 $this->update_user_level_from_caps();
680 * Remove all of the capabilities of the user.
685 * @global wpdb $wpdb WordPress database abstraction object.
687 public function remove_all_caps() {
689 $this->caps = array();
690 delete_user_meta( $this->ID, $this->cap_key );
691 delete_user_meta( $this->ID, $wpdb->get_blog_prefix() . 'user_level' );
692 $this->get_role_caps();
696 * Whether user has capability or role name.
698 * While checking against particular roles in place of a capability is supported
699 * in part, this practice is discouraged as it may produce unreliable results.
704 * @see map_meta_cap()
706 * @param string $cap Capability name.
707 * @param int $object_id,... Optional. ID of the specific object to check against if `$cap` is a "meta" cap.
708 * "Meta" capabilities, e.g. 'edit_post', 'edit_user', etc., are capabilities used
709 * by map_meta_cap() to map to other "primitive" capabilities, e.g. 'edit_posts',
710 * 'edit_others_posts', etc. The parameter is accessed via func_get_args() and passed
712 * @return bool Whether the current user has the given capability. If `$cap` is a meta cap and `$object_id` is
713 * passed, whether the current user has the given meta capability for the given object.
715 public function has_cap( $cap ) {
716 if ( is_numeric( $cap ) ) {
717 _deprecated_argument( __FUNCTION__, '2.0.0', __('Usage of user levels by plugins and themes is deprecated. Use roles and capabilities instead.') );
718 $cap = $this->translate_level_to_cap( $cap );
721 $args = array_slice( func_get_args(), 1 );
722 $args = array_merge( array( $cap, $this->ID ), $args );
723 $caps = call_user_func_array( 'map_meta_cap', $args );
725 // Multisite super admin has all caps by definition, Unless specifically denied.
726 if ( is_multisite() && is_super_admin( $this->ID ) ) {
727 if ( in_array('do_not_allow', $caps) )
733 * Dynamically filter a user's capabilities.
736 * @since 3.7.0 Added the user object.
738 * @param array $allcaps An array of all the user's capabilities.
739 * @param array $caps Actual capabilities for meta capability.
740 * @param array $args Optional parameters passed to has_cap(), typically object ID.
741 * @param WP_User $user The user object.
743 $capabilities = apply_filters( 'user_has_cap', $this->allcaps, $caps, $args, $this );
745 // Everyone is allowed to exist.
746 $capabilities['exist'] = true;
748 // Must have ALL requested caps.
749 foreach ( (array) $caps as $cap ) {
750 if ( empty( $capabilities[ $cap ] ) )
758 * Convert numeric level to level capability name.
760 * Prepends 'level_' to level number.
765 * @param int $level Level number, 1 to 10.
768 public function translate_level_to_cap( $level ) {
769 return 'level_' . $level;
773 * Set the site to operate on. Defaults to the current site.
777 * @global wpdb $wpdb WordPress database abstraction object.
779 * @param int $blog_id Optional. Site ID, defaults to current site.
781 public function for_blog( $blog_id = '' ) {
783 if ( ! empty( $blog_id ) )
784 $cap_key = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
787 $this->_init_caps( $cap_key );