I want to display a WordPress logged in user ID and email in another website so, I'm using the wordpress json-api
plugin to create an api but it's not working.
When I hit a direct link, it displays data as:
"{\"id\":1,\"email\":\"admin@admin.com\"}"
But when I use json_decode
and print data, it displays:
string(22) "{"id":0,"email":false}"
api code
public function get_loggedin_user_details() {
global $user;
global $wpdb, $json_api;
$current_user = wp_get_current_user();
$myObj->id = $current_user->ID;
$myObj->email = $current_user->user_email;
$logedin_userid = json_encode($myObj);
return $logedin_userid;
}
You are not authenticating your request, so the request is not logged, resulting in ID 0 and no email.
WP rest api provides a cookie authentication method, but there also plugins, you can read more on how-to here:
https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
Here the process to get the logged in user id on WP:
pass the login token you receive from the plugin to the route you created as Header: Authorization
create you custom Rest-API Route like this:
add_action( 'rest_api_init', function () { register_rest_route( 'your_custom_route/v2', '/(?P<slug>[a-zA-Z0-9-]+)', array( 'methods' => 'POST', 'callback' => 'rest_api_custom_func', ) ); } ); function rest_api_custom_func(){ global $user; global $wpdb; $current_user = wp_get_current_user(); $myObj->id = $current_user->ID; $myObj->email = $current_user->user_email; $logedin_userid = json_encode($myObj); return $logedin_userid; }
write your own function as a callback function on rest-api route : rest_api_custom_func
you can do whatever you want with your custom callback function
note: no need for any other plugin, use the built-in Wordpress Rest API
I'm going to point out something that maybe was just overlooked.
Your initial value is escaped... "{\\"id\\":1,\\"email\\":\\"admin@admin.com\\"}" and has quotes around the outside. It's not a proper json string.
Should be: {"id":1,"email":"admin@admin.com"}
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.