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.

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.

link|improve this question
Peter - you shouldn't need to load core files manually, please see my answer. Also - please post your solution as an answer, it makes it easier for people to distinguish between question and answers. – Stephen Harris Feb 24 at 1:22
feedback

2 Answers

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

    }     
}
link|improve this answer
that doesn't work either, I tried a lot but nothing seems to work. I've been stuck since a half day trying to accomplish it. In a theme it will work but in a plugin it doesn't i need to include a wordpress core file. But on my opinion it's a little bit ugly if i include some of wordpress core files. – CodingBear Feb 23 at 9:22
feedback

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

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.