Current user in plugin returns NULL

I am currently developing a plugin and I am trying to make use of the $current_user global.

class Something {
  public function __construct() {
    $this->get_user();
    var_dump( $this->user );
  }

 private function get_user() {
    require_once( ABSPATH . '/wp-includes/pluggable.php' );
    $this->user = wp_get_current_user();
  }
}

This actually works. However, I need to call pluggable.php file which shouldn’t be necessary. I have also tried calling the global $current_user variable to no avail: it always returns NULL… unless of course I import pluggable.php again – like so:

private function get_user() {
  require_once( ABSPATH . '/wp-includes/pluggable.php' );
  global $current_user;
  get_currentuserinfo();
  $this->user = $current_user;
}

This might be a potential duplicate of: $current_user var returns NULL

And I’ve tried all the solutions, but still need to import pluggable.php no matter what.

Seems like the author of the other thread found a solution that did not share.

Anybody else ever have this issue? Thanks.

1 Answer
1

Wait for the action plugins_loaded before you create the class instance. The pluggable functions are loaded at this time. From wp-settings.php:

/**
 * Fires once activated plugins have loaded.
 *
 * Pluggable functions are also available at this point in the loading order.
 *
 * @since 1.5.0
 */
do_action( 'plugins_loaded' );

I would even wait for wp_loaded in most cases. Then the global WP_Roles object has been set up, you know the theme and the locale – you will very likely not run again into a problem because of missing information.

Never just create class instances when your plugin’s main file is loaded. This always too early. Usually you want to check the request first to exclude your code from slowing down other plugins AJAX requests or WP’s comment/XML RPC/feed processing.

So your plugin’s main file could look like this:

add_action( 'wp_loaded', [ new Something, 'setup' ] );

Leave a Comment