简体   繁体   中英

Wordpress php can't get current user ID in a plugin

I have been struggling to get the current user ID in a wordpress plugin I am building. I have tried what seems to be everything, with still no luck.

The closest I have got is being able to return a '0' and then the user ID (so in the case of admin, I can return "ID: 0 ID: 1".

Here is the code that does that for me:

add_action('admin_init', 'myFunction');

function myFunction(){
    $user_ID= get_current_user_id();   
    echo "ID: ".$user_ID;
}

Obviously I have wrapped it in a function here that fires on admin init.

What's particularly strange is that in other files in my plugin, I am able to get user info using

global $current_user;
get_currentuserinfo();
$current_user->ID

But this trigger a fatal error

Fatal error: Call to undefined function get_currentuserinfo() 

...even if I wrap it in my function.

Surely this is a simple thing to achieve? Can anyone tell me how I do this

you need to first declare global variable $current_user then get the current user id

global $current_user; // declare the variable

echo $current_user->ID; // get the current longed in user ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM