Deep dive into WP_User class in WordPress
This article provides a detailed overview of the WP_User
class in WordPress. The WP_User
class represents a user object, providing access to user-related data and functionalities within the WordPress site. It encapsulates user attributes and methods, allowing developers to interact with and retrieve information about a specific user, such as their ID, username, email, roles, and capabilities. It also facilitates user-specific operations and customizations within WordPress sites or applications.
The WP_User class constructor
The WP_User class accepts the following parameters:
$id (int)
– the ID of the user$name (string)
– the username of the user$site_id (int)
– optional site ID in multi-site installations, it defaults to current site
You can initialize the WP_User class by setting the user ID or a user name. If both the $id
and $name
options are provided, the $name option will be ignored.
Instantiating WP_User with a user ID
To create an instance of WP_User class by user ID, simply pass the user ID as the first parameter to the constructor:
$user_id = 123; $user = new WP_User($user_id);
When the WP_User object is created, WordPress will query the database to find the user with ID 123. If the user exists, this object will contain all the information and methods associated with the user represented by the ID 123
.
Instantiating WP_User with a username
You can initialize the WP_User
class with a username by setting the user ID parameter to 0 and passing the username as a second parameter.
$username = 'john_doe'; $user = new WP_User(0, $username);
Checking if a user exists upon WP_User initialization
When initializing the WP_User class, it is important to check if a user exists with the given user ID/username. In this way, you can prevent unexpected behavior and errors further down your code when the user does not exist. You can do that by using the exists()
method on the $user
object:
$user_id = 123; $user = new WP_User($user_id); if ($user->exists()){ // user with ID 123 exists }
Functions returning WP_User object
In addition to instantiating the WP_User
class directly, you might have to work with WP_User
objects when other functions or methods return them. For example the get_user_by()
function returns a WP_User object on success:
$user = get_user_by('id', 123); // returns a WP_User object
Some of the most common functions that return WP_User are:
wp_get_current_user()
get_user_by()
get_userdata()
get_users()
– returns an array of WP_User objects
WP_User class properties
The WP_User class in WordPress encapsulates essential properties that store user-related data within the WordPress site. These properties contain crucial information such as user ID, username, email, roles, capabilities, and additional metadata.
The available properties of the WP_User class are, along with an explanation of what each of them means:
ID
– the ID of the useruser_login
– the username (user login) of the useruser_pass
– hashed passworduser_nicename
– URL sanitized version of usernameuser_email
– the email of the useruser_url
– the website of the useruser_registered
– registration dateuser_activation_key
– this is a key that is used for authenticity of a password reset requestdisplay_name
– the public display name of the userroles
– user roles, returned as an arraycaps
– user capabilities that have been assigned to the user outside those inherited from their roles. Returned as an associative array where the key is the capability name and value is a boolean representing whether the user has that capability.
The properties are directly assigned to the WP_User object, here is an example of retrieving the ID, username, and email of the current user:
$user = wp_get_current_user(); $user_id = $user->ID; $user_name = $user->user_login; $user_email = $user->user_email;
Retrieving user meta via class properties
In addition to the above-mentioned properties, all user meta values can be accessed directly as properties of the WP_User
object. Behind the scenes, this uses the __get()
magic method, which loads meta values based on dynamic property names.
For example, to load the user’s first name and last name fields, which WordPress stores as user meta with the keys first_name and last_name respectively, you can use the following code snippet:
$user = new WP_User($user_id); echo $user->first_name; echo $user->last_name;
In the same way, you can load values of custom meta keys. For example, if you need to retrieve a meta value for the meta key “phone_number”, you can access that via the “phone_number” property of the WP_User
object.
$user = new WP_User($user_id); echo $user->phone_number;
An empty string will be returned if no value is stored for the given meta key.
WP_User class methods
This section delves into the practical usage of WP_User
class methods in WordPress development. These methods efficiently retrieve, modify, and manage user attributes, enabling various user-related operations within WordPress.
Gain Valuable Insights From Your WordPress User Data
Methods for retrieving user data and meta
get()
– the get() method is another way that can be used to load user data. This method can load user properties, core meta data and custom user meta data. For example:
$user = new WP_User($user_id); echo $user->get('user_login'); // get username echo $user->get('first_name'); // get first name echo $user->get('phone_number'); // get custom meta value stored with key "phone_number"
has_prop()
can be used to check if the user object has a given property or meta key set. This method uses the__isset()
magic method behind the scenes.
$user = new WP_User($user_id); $user->has_prop('user_login'); // true $user->has_prop('first_name'); // true $user->has_prop('inexisting'); // false
Role methods
The WP_User class provides method to manage the roles of a user fully. These methods include:
add_role( string $role )
– adds a role to the userremove_role( string $role )
– removes a role from the userset_role( string $role )
– removes existing roles and sets the role passed as a parameter
The following example illustrates how to manage to use these methods to manage the roles of an individual user:
$user = new WP_User($user_id); print_r($user->roles); // defaults ['subscriber'] // add a role $user->add_role('member'); print_r($user->roles);// ['subscriber', 'member'] // remove a role $user->remove_role('member'); print_r($user->roles); // ['subscriber'] // set role $user->set_role('member'); print_r($user->roles); // ['member']
Capability methods
Similarly to roles, you can also manage the capabilities of a user using the WP_User class capability methods:
add_cap( string $cap, bool $grant = true )
– add capability to the user. This method accepts an additional$grant
parameter which defines whether to grant access to this capability to the user. The default value is true, so you can omit this parameter when you intend to grant access to this capability. This method is persistent, meaning that the new capability will be stored in the database.remove_cap( string $cap )
– remove capability from the user. This method also persists the changes in the database.remove_all_caps()
– removes all capabilities from the user
Here are examples of adding and removing capabilities to a user object:
$user_id = 123; $user = new WP_User($user_id); print_r($user->caps); // ['subscriber' => true] // add the "edit-posts" capability $user->add_cap('edit_posts'); print_r($user->caps);// ['subscriber' => true, 'edit_posts' => true] // remove the "edit-posts" capability $user->remove_cap('edit_posts'); print_r($user->caps); // ['subscriber' => true]
has_cap( string $cap, mixed $args )
– this method can be used to check whether the user has a given capability.
It is most commonly used by passing the capability name parameter only:
$user->has_cap( 'edit_posts' );
However, in some cases, it can be invoked with additional parameters. For example, if you need to check if a user can edit a specific post, you can invoke the method like this:
$user->has_cap( 'edit_post', $post->ID );
get_role_caps()
– this method returns a list of all the user’s capabilities, including those that are inherited from the user role
Conclusion
In summary, exploring the WP_User
class revealed its crucial role in managing user-related tasks in WordPress. Understanding its properties and methods helps developers handle user data, roles, and interactions effectively. Mastering this class allows better customization and management of user information, enhancing WordPress websites and applications for improved user experiences.