Unable to get current user ID (6 posts)

  1. boybawang
    Posted 3 years ago #

    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?

  2. 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?

  3. boybawang
    Posted 3 years ago #

    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?

  4. 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.

  5. boybawang
    Posted 3 years ago #

    Thanks for the suggestion Josh, but I had no luck :(

  6. boybawang
    Posted 3 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic