wp_get_current_user in custom file returns 0

The problem with your code is that you want to get current user to early.

wp_get_current_user is using global current_user variable.

But this variable isn’t set from the beginning.

And if you want to use this function straight in the script file, then it’s to early.

You should wait for init action to get current user.

require($_SERVER['DOCUMENT_ROOT'].'/wp-config.php'); 
require($_SERVER['DOCUMENT_ROOT'].'/wp-load.php'); 

add_action( 'init', function() {
    $current_user = wp_get_current_user(); 
    var_dump($current_user->ID);
    var_dump($current_user->display_name);
});

Leave a Comment