WordPress.org

Ready to get started?Download WordPress

Forums

$current_user global - Is it automatically loaded? (3 posts)

  1. J.D. Grimes
    Member
    Posted 1 year ago #

    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.

  2. OrgoneTX
    Member
    Posted 9 months ago #

    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);
  3. J.D. Grimes
    Member
    Posted 9 months ago #

    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).

Topic Closed

This topic has been closed to new replies.

About this Topic