Semyon Tikhonenko Semyon Tikhonenko -4 years ago 397
PHP Question

How to get current logged in user using Wordpress Rest Api?

I tried to add a custom request.

add_action('rest_api_init', function () {
register_rest_route( 'custom', '/login', array(
'methods' => 'GET',
'callback' => function(WP_REST_Request $request) {
return wp_get_current_user();
}
));
});


But it always returns a user with with ID = 0;
I also tried this:

add_action('rest_api_init', function () {
register_rest_route( 'custom', '/login', array(
'methods' => 'GET',
'callback' => function(WP_REST_Request $request) {
return is_user_logged_in();
}
));
});


And it always returns false.
But the user is logged in for sure.

I added my custom login

add_action('rest_api_init', function () {
register_rest_route( 'custom', '/login', array(
'methods' => 'POST',
'callback' => function(WP_REST_Request $request) {
$nonce = wp_create_nonce("wp_rest");
$user = wp_signon(array('user_login' => $_POST['username'],
'user_password' => $_POST['password'], "rememberme" => true), false);
if (is_wp_error($user)) {
return $user;
}

//do_action( 'wp_login', "capad" );
//$user['isloggedin'] = is_user_logged_in();
return array('user' => $user,
'nonce' => $nonce);
}
));
});


And I add "X-WP-Nonce" in as a header for http request

And now every request outputs:
{"code":"rest_cookie_invalid_nonce","message":"Cookie nonce is invalid","data":{"status":403}}

Answer Source

I get it work. The problem was here

$user = wp_signon(array('user_login' => $_POST['username'],
                'user_password' => $_POST['password'], "rememberme" => true),true);

I just replaced the 3d param with true.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download