I’m trying to figure out how to retrieve a user’s roles from the API, but I haven’t been able to sort it. Is this information not accessible by default?
Can anyone point me in the right direction?
I’m trying to figure out how to retrieve a user’s roles from the API, but I haven’t been able to sort it. Is this information not accessible by default?
Can anyone point me in the right direction?
This is totally possible by registering your own rest field into the response.
Here’s some documentation on modifying response data.
https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/
Here’s how to add roles to the endpoint:
function get_user_roles($object, $field_name, $request) {
return get_userdata($object['id'])->roles;
}
add_action('rest_api_init', function() {
register_rest_field('user', 'roles', array(
'get_callback' => 'get_user_roles',
'update_callback' => null,
'schema' => array(
'type' => 'array'
)
));
});
Specifically, what I’m doing is creating a function called get_user_roles
that retrieves the user roles, then registering a ‘roles’ field in the response, and tell it that the data comes from that function.
I also ran into an issue of it not playing nice when the data returned an array
, so I told the schema to expect it in the schema
property of the array passed in register_rest_field