How do I call wp_get_current_user() in a plugin when plugins are loaded before pluggable.php?

To add to @EAMann’s answer, you need to wrap your wp_get_current_user() call (or any call that tries to access a function defined within pluggable.php) within the 'plugins_loaded' action.

So, if you’re putting this inside your functions.php file, do it like this:

add_action( 'plugins_loaded', 'get_user_info' );

function get_user_info(){
  $current_user = wp_get_current_user(); 

  if ( !($current_user instanceof WP_User) ) 
    return; 

  echo $current_user->user_login;

  // Do the remaining stuff that has to happen once you've gotten your user info
}

Do note that we’re not interested in what this function returns. We’re interested in when this function executes, namely, after the pluggable.php file has loaded and defined your wp_get_current_user() function.

So, don’t expect to do anything with the return value for this function. Instead, consider this function as the starting point for everything that you want to do once you’ve got the current user’s info.

Doing it in a plugin

For the sake of completeness, here’s how you would access a similar pluggable function from within the context of your own plugin:

(put this inside a .php file inside your plugins folder)

class WPSE_58429 {
    public function __construct(){
        add_action( 'plugins_loaded', array( $this, 'check_if_user_logged_in' ) );
    }

    public function check_if_user_logged_in(){
        if ( is_user_logged_in() ){
           // ... do stuff for your logged-in user
        }
    }
}

$wpse_58429_plugin = new WPSE_58429();

I’ve used this technique successfully for a very simple “Coming Soon” type of plugin that redirects the user to a specific page if they’re not logged in using wp_safe_redirect().

Leave a Comment