我的目标是限制每种自定义帖子类型的某些RESTUL动词。例如,给定一个Vocabulary自定义帖子类型,我想说:
权限矩阵
+-------+---+----------+
|index  | X | GET      |
|show   | O | GET      |
|create | X | POST     |
|update | X | PATCH/PUT|
|delete | X | DELETE   |
+-------+---+----------+V2似乎没有提供这种级别的控制。我已经浏览了源代码,从我所看到的内容来看,没有任何挂钩/过滤器可用于更改权限。
我当前的解决方案如下。它损害了一个类,您可以在该类中针对允许的操作加载自定义帖子类型的矩阵。然后可以在rest_prepare_vocabulary过滤器中调用此方法,如果权限不匹配,则会破坏响应。
问题
我觉得这不是一个合理的解决方案。这意味着权限在两个位置(一个仍在应用中,处于核心位置)和我的过滤器中得到解决。
理想情况下,它将位于配置级别,即定义自定义帖子类型的位置。
换句话说,我宁愿传递规则(沿的线条exclude_from_search,publicly_queryable等等),而不是执行后查询“喀嚓”。
当前解决方案(可行但不理想)
Access.php
class Access
{
    function __construct($permissions) {
        $this->permissions = $permissions;
    }
    protected function hasId($request) {
        return ! is_null($request->get_param('id'));
    }
    protected function resolveType($request) {
        $method = strtoupper($request->get_method());
        if($method === 'GET' && $this->hasId($request)) {
            return 'show';
        } else if($method === 'GET') {
            return 'index';
        } else if($method === 'DELETE') {
            return 'delete';
        } else if($method === 'POST') {
            return 'create';
        } else if($method === 'PATCH') {
            return 'update';
        }
    }
    function validate($type, $request) {
        return in_array($this->resolveType($request), $this->permissions[$type]);
    }
}functions.php
// bootstrap the permissions for this particular 
// application
// 
$access = new Access([
    'vocabulary' => ['show'],
]);
add_filter('rest_prepare_vocabulary', 'validate_permissions', 30, 3);
function validate_permissions($response, $post, $request) {
    global $access;
    // Give access->validate the type + request data 
    // and it will figure out if this is allowed
    //
    if( ! $access->validate($post->post_type, $request)) {
        $response->set_data([]);
        $response->set_status(403);
    }
    return $response;
};\Appand访问实际上是\App\Services\Access
                
Access在全局范围内实例化?您是否需要其他地方?如果使用yes回答,则可能需要将其附加到过滤器。