get_current_user_id()

Get the current user’s ID


Description Description


Return Return

(int) The current user's ID, or 0 if no user is logged in.


Top ↑

Source Source

File: wp-includes/user.php

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 );
}

Top ↑

Changelog Changelog

Changelog
Version Description
MU (3.0.0) Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 4 content
    Contributed by Aurovrata Venet

    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.

  2. Skip to note 5 content
    Contributed by Mário Valney

    SoN9ne is right, but as we are in get_current_user_id‘s documentation make senses that example (even just for knowledge).

    This way we can query for draft posts of a current user:

    $query = new WP_Query( array(
        'author'        => get_current_user_id(),
        'post_status'   => 'draft'
    ) ); 

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