Support » Fixing WordPress » Unable to get current user ID

  • Hello –
    I’m pretty new to wordpress. I’m trying to get the current user ID in one of my plugin pages. I’ve tried wp_get_current_user()->ID, but that’s returning 0. From what I’ve read, I realize that this page is being loaded prior to the aforementioned wrapper, and that I probably need a hook to get it properly. I really have no clue what I’m doing with hooks, so if somebody could shed some light on this I’d appreciate it. Is wp_login the best hook to use?
    Why is it that in some of my plugin pages I’m able to get the current user using wp_get_current_user() but some pages I can’t?

Viewing 5 replies - 1 through 5 (of 5 total)
  • It depends on how your files are structured in relation to WP. Is it your main .php file that you are using the wp_get_current_user() function? Or is it a file… deeper in your plugin folder?

    The file is definitely deeper in my plugin folder than the main php file. Should I be including a file at the top of the .php file?

    Yeah.. I think you’re trying to define the variable before pluggable.php has been loaded.

    Okay.. in the main file of your plugin… where you know wp_get_current_user() is working… let’s add this function:

    function getCurUser() {
        // Get the current user's info
        $current_user = wp_get_current_user(); 
        if ( !($current_user instanceof WP_User) )
        return $current_user->user_login;

    Then, when you need to get the current user id.. just use this in your code:

    $getID = getCurUser();

    I haven’t tested… but it might solve your problem.

    Thanks for the suggestion Josh, but I had no luck 🙁

    Hey Josh – I figured it out. There was actually a class that I overlooked that I was able to retrieve the user ID from.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Unable to get current user ID’ is closed to new replies.