WordPress at a glance

get_current_user_id() WP 3.0.0

Get the current user's ID.

Works based on: wp_get_current_user()
✈ 1 time = 0.000012s = very fast | 50000 times = 0.01s = speed of light PHP 7.1.2, WP 4.7.4

No Hooks.

Return

Int. The current user's ID, or 0 if no user is logged in.

Usage

get_current_user_id();

Examples

#1 Get current user ID for further processing

$cur_user_id = get_current_user_id();
echo $cur_user_id; //> 5

Code of get_current_user_id: wp-includes/user.php VER 4.9.8

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

Related Functions

From tag: Users (_user)

More from category: Other

4 comments
  • I'm doing prohrammatic login using

    function programmatic_login( $username ) {
    	if ( is_user_logged_in() ) {
    		wp_logout();
    	}
    
    	add_filter( 'authenticate', 'allow_programmatic_login', 10, 3 );    // hook in earlier than other callbacks to short-circuit them
    	$user = wp_signon( array( 'user_login' => $username ) );
    	remove_filter( 'authenticate', 'allow_programmatic_login', 10, 3 );
    
    	if ( is_a( $user, 'WP_User' ) ) {
    		wp_set_current_user( $user->ID, $user->user_login );
    
    		if ( is_user_logged_in() ) {
    			return true;
    		}
    	}
    
    	return false;
    }

    when I check current user details on the same page it is providing me the correct details "BUT" when I using get_current_user_id() function on another page it is giving me zero. Any help would means a lot.

    1
    • kama100

      What does prohrammatic login mean? What allow_programmatic_login function code is? There are so many questions to answer your question - it's not clear unknw

      • Hello Kama it's really fortunate that you have replied. I have made a custom registration and login page in for my wordpress site. So after a successful login I'm trying to set my current user details in session via wp_set_current_user() on my login page so that I can access it at any page I want . When I'm using above code I get the details on the same page where I'm setting these values but whenever I redirect to any other page on my website get_current_user_id() function returns zero which all that session data is lost. If you could suggest any technique using which I could retrieve these details would really help me alot.

        • kama100

          Do you use default WordPress logic for authentication?

          It seems you need to set authentication cookies after user login and password have been cheked. Use wp_set_auth_cookie() function to do it. Without setting such cookies - it is equivalent to the fact that the user is not logged.

Hello, !     Log In . Register