I need to access logged-in user data in a custom PHP file that I call in a WP page through an include.

The include file is:

require($_SERVER['DOCUMENT_ROOT'].'/wp-config.php'); 
require($_SERVER['DOCUMENT_ROOT'].'/wp-load.php'); 
$current_user = wp_get_current_user(); 
var_dump($current_user->ID);
var_dump($current_user->display_name);

And it outputs:
int(0) bool(false) int(0) bool(false)

However… In the very same page, I also call a function that I entered in function.php:

$current_user = wp_get_current_user();
var_dump($current_user->ID);
var_dump($current_user->display_name);

And this one outputs:
int(1) string(10) “antoine251”

It looks to me like WP functions called from my external php file are not working.

What am I missing?
(No pluggin is even installed, same results in twentynineteen theme than is my custom theme)

Thanks in advance for your help!

1 Answer
1

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);
});

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *