0

I am writing my own plugin and I am stuck quite early on. I am trying to get the ID of currently logged in user, via php script. Something like this

add_action('init','do_stuff');
function do_stuff(){
    $current_user = wp_get_current_user();
    // rest of my code here
}

However I am always getting the result 0.

I am aware that there are multiple similar questions, but literally no solutions worked so far. E.g.

wp_get_current_user always returns 0

wp_get_current_user() function not working in Rest API callback function

wp_get_current_user always returns 0 continued

1 Answer 1

0

Instead of using init hook why don't you use the wp_loaded hook. This way, you're sure that everything is loaded

add_action('wp_loaded','do_stuff');
function do_stuff(){
    $current_user = wp_get_current_user();
    if ($current_user->ID > 0) {
        // rest of your code here
        // $current_user->ID will give you the ID of the current user.
    }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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