get_current_user_id(): int

Gets the current user’s ID.

Return

int The current user’s ID, or 0 if no user is logged in.

Source

function get_current_user_id() {
	if ( ! function_exists( 'wp_get_current_user' ) ) {
		return 0;
	}
	$user = wp_get_current_user();
	return ( isset( $user->ID ) ? (int) $user->ID : 0 );
}

Changelog

VersionDescription
MU (3.0.0)Introduced.

User Contributed Notes

  1. Skip to note 10 content

    Get current user ID, if the user is logged in.

    if ( is_user_logged_in() ) {
        echo 'User ID: ' . get_current_user_id();
    } else {
        echo 'Hello visitor!';
    }
  2. Skip to note 11 content

    This function is not means for retrieving the current logged in user as it been made abundently clear some of the examples so far.

    It is however very useful for validation of existing users’ emails, consider the following example,

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

    in this case a form is used to allow users to change their registered email, and one can validate the change by making sure that the new submitted email is not already in use and does not belong to the current user.

You must log in before being able to contribute a note or feedback.