I am unable to get the user info from the REST API. The user has not any post created. I have installed the Basic-Auth plugin. Whenever I try to get the user info, I get the following error.
Request : https://example.com/wp-json/wp/v2/users/6
{
"code": "rest_user_cannot_view",
"message": "Sorry, you are not allowed to list users.",
"data": {
"status": 401
}
}
But whenever I request the other user, I get the info.
{
"id": 1,
"name": "asdf",
"url": "",
"description": "",
"link": "https://example.com/author/drzvikrant/",
"slug": "asdf",
"avatar_urls": {
"24": "https://secure.gravatar.com/avatar/4bc329d2835e6584d5b492fdc67a5cde?s=24&d=mm&r=g",
"48": "https://secure.gravatar.com/avatar/4bc329d2835e6584d5b492fdc67a5cde?s=48&d=mm&r=g",
"96": "https://secure.gravatar.com/avatar/4bc329d2835e6584d5b492fdc67a5cde?s=96&d=mm&r=g"
},
"meta": [],
"_links": {
"self": [
{
"href": "https://example.com/wp-json/wp/v2/users/1"
}
],
"collection": [
{
"href": "https://example.com/wp-json/wp/v2/users"
}
]
}
}
I need to get the user info, even if the user have not created any posts.
1 Answer
This is by design and within WP_REST_Users_Controller::get_item_permissions_check()
we e.g. have a non-zero check with count_user_posts( $user->ID, $types )
.
We note that count_user_posts()
is filterable with the get_usernumposts
filter so one could change 0 to 1, for the /wp/v2/users/\d+
route:
add_filter( 'rest_request_before_callbacks', function( $response, $handler, $request ){
if ( WP_REST_Server::READABLE !== $request->get_method() ) {
return $response;
}
if ( ! preg_match( '~/wp/v2/users/\d+~', $request->get_route() ) ) {
return $response;
}
add_filter( 'get_usernumposts', function( $count ) {
return $count > 0 ? $count : 1;
} );
return $response;
}, 10, 3 );
but I would rather recommend creating a custom rest route instead of modifying an existing one like this.