• I am working on writing a plugin, in which I need to get the current logged in user’s ID. I know that I can do this like so with the $current_user global:

    global $current_user;
    $userID = $current_user->ID;

    There are several places in the plugin where I need this. My question is, can I count on this global always being loaded, i.e., is it loaded automatically by WordPress on each run? Or do I need to check if it’s set and then call get_currentuserinfo() if it isn’t?

    global $current_user;
    get_currentuserinfo();
    echo $current_user->ID;

    I don’t want to be calling the get_currentuserinfo() function unnecessarily (though I guess it really wouldn’t make that much difference), and I couldn’t find anything definite in the documentation.

Viewing 2 replies - 1 through 2 (of 2 total)
  • I had to include the file.

    require (ABSPATH . WPINC . '/pluggable.php');

    Then it all works.

    global $current_user;
    \get_currentuserinfo(); // the slash is because I use namespaces and called this from within a plugin.
    echo "userid is " . $current_user->UUID;
    var_dump($current_user);

    I’ve found that the current user will be set up on each page load, and can safely be accessed from 'init' and later by calling wp_get_current_user(). The only time you would need to implement code such as I posted above would be if you must have the current user’s info before 'init' (for example, on 'plugins_loaded' action).

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘$current_user global – Is it automatically loaded?’ is closed to new replies.