$current_user var returns NULL

I am developing an wp plugin and I am trying to get the current user.

If i return with an error print_r($current_user) returns the needed info.

Read More

But the plugin is activated without an error it returns NULL.

I tried to include some wp core files such as wp-load etc but this doesn’t have any effect.

this is my code(without the error):

class My_plugin_class{

    var $user;

    function __construct() 
    {
        global $current_user;

        //Set the current user
        $this->user = $current_user;

        print_r($this->user);

    }     
}

EDIT:
Just edited my code to:

require_once(ABSPATH . '/wp-includes/pluggable.php');
global $current_user;
get_currentuserinfo();

The function get_currentuserinfo() does now a print_r(); and isn’t going to stop?

EDIT:
Fixed it myself.

Related posts

Leave a Reply

2 comments

  1. You need to globalize $current_user, and then populate it via get_currentuserinfo(). See the Codex entry for get_currentuserinfo(). In the Codex-example usage:

    <?php
    global $current_user;
    get_currentuserinfo();
    ?>
    

    So, try adapting your code accordingly; e.g.:

    class My_plugin_class{
    
        var $user;
    
        function __construct() 
        {      
            //Set the current user
            global $current_user;
            get_currentuserinfo();
            $this->user = $current_user;
    
            print_r($this->user);
    
        }     
    }
    
  2. You shouldn’t have to manually require WP files. You are probably just using the function too early, try constructing the class on init or have your __construct function hook a second function on init that deals with the current user.

    For instance:

    class My_plugin_class{
    
        var $user;
    
        function __construct() {      
            add_action('init',array(__CLASS__,'init'));
        }     
    
        static function init(){
            //Set the current user
            global $current_user;
            get_currentuserinfo();
            $this->user = $current_user;
            print_r($this->user);
        }
    }
    My_plugin_class::__construct;
    

    Not tested