Using WordPress ‘get_current_user_id()’ PHP function

The get_current_user_id() WordPress PHP function retrieves the ID of the currently logged-in user.

Usage

$current_user_id = get_current_user_id();

Parameters

  • None

More information

See WordPress Developer Resources: get_current_user_id()

Examples

Displaying a greeting message based on user login

$current_user_id = get_current_user_id();

if ($current_user_id) {
    echo 'Welcome back, registered user!';
} else {
    echo 'Hello, visitor!';
}

Getting the current user’s role

$current_user_id = get_current_user_id();
$user = new WP_User($current_user_id);
$current_user_role = $user->roles[0];

echo "Your role is: $current_user_role";

Querying draft posts of the current user

$current_user_id = get_current_user_id();

$args = array(
    'author' => $current_user_id,
    'post_status' => 'draft'
);

$query = new WP_Query($args);

Displaying the user ID if the user is logged in

$current_user_id = get_current_user_id();

if ($current_user_id) {
    echo "User ID: $current_user_id";
} else {
    echo 'Hello visitor!';
}

Validating user email for uniqueness

$email = $_POST['contact-email'];
$current_user_id = get_current_user_id();

if (($user = email_exists($email)) && $user !== $current_user_id) {
    $validation['contact-email'] = 'This email has already been registered, please contact us!';
}