Disable part of endpoints wordpress api
-
20-05-2021 - |
Вопрос
I try to disable some parts of the API :
- display list of users
- display detail of users
But i want to keep the api to create and update users.
I did this :
add_filter( 'rest_endpoints', 'disable_custom_rest_endpoints' );
function disable_custom_rest_endpoints( $endpoints ) {
if ( isset( $endpoints['/wp/v2/users'] ) ) {
unset( $endpoints['/wp/v2/users'] );
}
if ( isset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] ) ) {
unset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] );
}
return $endpoints;
}
My problem : this delete the possibility to update or create user as well
Is there another way to do it ?
Thanks
Решение
The routes in question have two or three default endpoints:
/wp/v2/users
— it has two endpoints, one GET and one POST, i.e. "List Users" (GET /wp/v2/users
), and "Create a User" (POST /wp/v2/users
)./wp/v2/users/<id>
— it has three endpoints, one GET, one POST and one DELETE, i.e. "Retrieve a User" (GET /wp/v2/users/<id>
), "Update a User" (POST /wp/v2/users/<id>
), and "Delete a User" (DELETE /wp/v2/users/<id>
).
So in your code, you can unset the array (which represents an endpoint with specific HTTP request methods) in a route, if the request method is GET.
Working Example
function disable_custom_rest_endpoints( $endpoints ) {
$routes = array( '/wp/v2/users', '/wp/v2/users/(?P<id>[\d]+)' );
foreach ( $routes as $route ) {
if ( empty( $endpoints[ $route ] ) ) {
continue;
}
foreach ( $endpoints[ $route ] as $i => $handlers ) {
if ( is_array( $handlers ) && isset( $handlers['methods'] ) &&
'GET' === $handlers['methods'] ) {
unset( $endpoints[ $route ][ $i ] );
}
}
}
return $endpoints;
}
Tried & tested working on WordPress 5.7.2 — only the GET /wp/v2/users
and GET /wp/v2/users/<id>
endpoints got removed/disabled.