Using WordPress ‘get_userdata()’ PHP function

The get_userdata() WordPress PHP function retrieves user information based on the user ID.

Usage

get_userdata( $user_id )

Example:

$user_info = get_userdata(1);
echo 'User ID: ' . $user_info->ID;

Output:

User ID: 1

Parameters

  • $user_id (int) – Required. The user ID for which you want to retrieve the user data.

More information

See WordPress Developer Resources: get_userdata()

Examples

Displaying User Login

Retrieve and display the user’s login name:

$user_info = get_userdata(1);
echo 'Username: ' . $user_info->user_login;

Displaying User Roles

Retrieve and display the user’s assigned roles:

$user_info = get_userdata(1);
echo 'User roles: ' . implode(', ', $user_info->roles);

Displaying User’s Display Name and Email

Retrieve and display the user’s display name and email address:

$user_info = get_userdata(1);
$user_name = $user_info->display_name;
$user_email = $user_info->user_email;
echo $user_name . ', ' . $user_email;

Displaying User’s First and Last Name

Retrieve and display the user’s first and last name:

$user_info = get_userdata(1);
echo $user_info->first_name . ' ' . $user_info->last_name;

Storing User Data in Variables

Store user data in variables for later use or display in multiple places:

$user_info = get_userdata(1);
$username = $user_info->user_login;
$first_name = $user_info->first_name;
$last_name = $user_info->last_name;
echo "$first_name $last_name logs into her WordPress site with the user name of $username.";