• I have an installation of WordPress que I use for the blog and in the directory, I have an application developed in PHP. To avoid redundancy I use the login of web to get access to this app, so people registered in WP, can see the content Within this app.

    Before the last update to 4.2 WP, it used to work perfectly but now it does not.

    In the header of my PHP I used the following code to get the user_id:

    require_once(‘../../wp-blog-header.php’);
    $userID = get_current_user_id();
    print_r($userID);
    if ( $userID<=0 ) {
    //header(‘location: /login/’);exit(0);
    }

    It doesn’t work, the user_id = 0.

    I think something changed the way WP manage the sessions or something like that.

    Does anyone know how can i solve this?

    Thanks in advance.

Viewing 6 replies - 1 through 6 (of 6 total)
  • I believe it’s recommended to use is_user_logged_in() for this:

    https://codex.www.ads-software.com/Function_Reference/is_user_logged_in

    Thread Starter alxnet

    (@alxnet)

    karpstrucking, in that application developed i need to get user id not only to check if user is logged in.

    I am also getting a 0 return from get_current_user_id() since updating. I’m using a plugin and that’s how I was setting the current user.

    UPDATE
    Seems to work if I move get_current_user_id() to the a page that get called via shortcode.

    Just had this myself when refactoring a plugin I’m writing.
    I moved the get_current_user_id out of a method into the constructor of my plugin object and it suddenly started to return 0.

    Looks like when the plugin is instantiated the get_current_user_id method doesn’t exist yet (i.e. not loaded by WordPress yet) so it returns 0.

    /**
     * Get the current user's ID
     *
     * @since MU
     *
     * @return int The current user's ID
     */
    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 );
    }

    I’ll bet that’s what is happening here and that 4.2 has refactored when core functions are loaded.

    I believe that was my issue too. I made a function, called in WP globals, and was able to get current user data.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘get_current_user_id() returns 0’ is closed to new replies.