get_user()
Gets a user object based on its numeric ID.
This is a convenience wrapper around get_user_by( 'id', $user_id ) when you specifically need to search by ID.
Notes:
- If 0 or a non-existent ID is passed,
falsewill be returned, so always check the returned value usinginstanceofor=== falsebefore working with it. - The result is cached in the object cache.
Uses: get_user_by()
No Hooks.
Returns
WP_User|false.
- A WP_User object with the user's data.
falseon search error — when 0 or a non-existent ID is passed.
Usage
get_user( $user_id );
- $user_id(int) (required)
- The number of the user to retrieve.
Examples
#1 Get a user by ID
$user = get_user( 42 );
if( $user ){
echo esc_html( $user->display_name );
} #2 Current authenticated user
Combined with get_current_user_id() it is possible to safely get the current user object.
$current_user = get_user( get_current_user_id() );
if ( $current_user ) {
// Work with data
/*
WP_User Object (
[ID] => 10
[data] => stdClass Object (
[ID] => 10
[user_login] => my_login
[user_pass] => $P$B/Nlwo345D6___MNOMdT66.x0
[user_nicename] => my_login
[user_email] => [email protected]
[user_url] =>
[user_registered] => 2010-03-26 09:27:40
[user_activation_key] => 16212384:$P$By__aWu.Pe4Uw.MUh__59zc1
[user_status] => 1760048562
[display_name] => User Name
)
[caps] => Array (
[administrator] => 1
)
[cap_key] => wp_capabilities
[roles] => Array(
[0] => administrator
)
[allcaps] => Array(
[switch_themes] => 1
[edit_themes] => 1
[activate_plugins] => 1
[edit_plugins] => 1
[edit_users] => 1
[edit_files] => 1
[manage_options] => 1
...
)
[filter] =>
[site_id:WP_User:private] => 1
)
*/
} #3 Handling when a user is not found
The example demonstrates how to correctly handle the situation when a user is not found.
$user = get_user( 999 );
if ( ! $user ) {
wp_die( 'User not found' );
}
Changelog
| Since 6.7.0 | Introduced. |
get_user() get user code WP 6.9
function get_user( $user_id ) {
return get_user_by( 'id', $user_id );
}