Using WordPress ‘get_user_by()’ PHP function

The get_user_by() WordPress PHP function retrieves user information by a given field such as user ID, slug, email address, or login name.

Usage

get_user_by($field, $value);

Parameters

  • $field (string) – The field to retrieve the user with. Options are: id | ID | slug | email | login.
  • $value (int|string) – A value for the field. A user ID, slug, email address, or login name.

More information

See WordPress Developer Resources: get_user_by()

Examples

Get user information by user ID

$user_id = 1;
$user = get_user_by('id', $user_id);
echo 'User Display Name: ' . $user->display_name;

Get user information by email address

$email = '[email protected]';
$user = get_user_by('email', $email);
echo 'User Display Name: ' . $user->display_name;

Get user information by slug

$slug = 'john-doe';
$user = get_user_by('slug', $slug);
echo 'User Display Name: ' . $user->display_name;

Get user information by login name

$login_name = 'johndoe';
$user = get_user_by('login', $login_name);
echo 'User Display Name: ' . $user->display_name;

Check if user is an administrator

$user_id = 1;
$user = get_user_by('id', $user_id);
if (in_array('administrator', $user->roles)) {
    echo 'User is an Administrator';
} else {
    echo 'User is not an Administrator';
}