禁用部分终结点WordPress API

时间:2021-05-17 作者:djoo

我尝试禁用API的某些部分:

显示用户列表显示用户详细信息,但我想保留创建和更新用户的api。

我做到了:

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;
}
我的问题:这删除了更新或创建用户的可能性

还有别的方法吗?

谢谢

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

所讨论的路由有两个或三个默认端点:

  • /wp/v2/users — 它有两个端点,一个GET和一个POST,即“GET”;列出用户“;(GET /wp/v2/users), 和;创建用户“;(POST /wp/v2/users).

  • /wp/v2/users/<id> — 它有三个端点,一个GET、一个POST和一个DELETE,即;检索用户“;(GET /wp/v2/users/<id>), "E;“更新用户”;(POST /wp/v2/users/<id>), 和;删除用户“;(DELETE /wp/v2/users/<id>).

    因此,在代码中,如果请求方法为GET,则可以在路由中取消设置数组(表示具有特定HTTP请求方法的端点)。

    工作示例

    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;
    }
    
    尝试(&T);已在WordPress 5.7.2上测试-仅GET /wp/v2/usersGET /wp/v2/users/<id> 已删除/禁用终结点。