0

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

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.