Wordpress WP REST API为现有端点设置权限
我有一个自定义的post类型,Wordpress WP REST API为现有端点设置权限,wordpress,rest,wordpress-rest-api,Wordpress,Rest,Wordpress Rest Api,我有一个自定义的post类型,card,我正在通过WP-restapi公开它 function register_card_post_type() { $labels = array( "name" => __( 'Cards', '' ), "singular_name" => __( 'Card', '' ), ); $args = array( "label" => __( 'Cards', ''
card
,我正在通过WP-restapi公开它
function register_card_post_type() {
$labels = array(
"name" => __( 'Cards', '' ),
"singular_name" => __( 'Card', '' ),
);
$args = array(
"label" => __( 'Cards', '' ),
"labels" => $labels,
"description" => "",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"show_in_rest" => true, // ADD TO REST API
"rest_base" => "cards", // ADD TO REST API
"has_archive" => false,
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "post",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "card", "with_front" => true ),
"query_var" => true,
"menu_position" => 5,
"supports" => array( "title" ),
);
register_post_type( "card", $args );
}
add_action( 'init', 'register_card_post_type' );
默认情况下,端点是公共的。如何设置端点的身份验证要求,以便GET/cards/
需要身份验证cookie或标头
API手册中介绍了如何编写自定义端点,但理想情况下,是否有一个过滤器或钩子可用于扩展自动生成的端点
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
'args' => array(
'id' => array(
'validate_callback' => 'is_numeric'
),
),
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
} );
add_操作('rest_api_init',函数(){
注册rest路由('myplugin/v1','/author/(?P\d+),数组(
'方法'=>'获取',
“回调”=>“我的超级棒”,
“args”=>数组(
'id'=>数组(
“验证回调”=>“是数值”
),
),
“权限\回调”=>函数(){
返回当前用户可以编辑的内容(“编辑其他文章”);
}
) );
} );
您可以使用rest\u pre\u dispatch
过滤器检查URL,并撤销未登录用户对该端点的访问权:
add_filter( 'rest_pre_dispatch', function() {
$url = strtok($_SERVER["REQUEST_URI"],'?');
if ( !is_user_logged_in() &&
!in_array($url, array ( //using "in_array" because you can add mmultiple endpoints here
"/wp-json/cards",
))){
return new WP_Error( 'not-logged-in', 'API Requests to '.$url.' are only supported for authenticated requests', array( 'status' => 401 ) );
}
} );
这不是最好的解决方案,因为它将运行查询并过滤结果,但我一直在使用它,直到发现在执行查询之前阻止API访问的方法。您可以使用
rest\u pre\u dispatch
过滤器检查URL并撤销未登录用户对该端点的访问:
add_filter( 'rest_pre_dispatch', function() {
$url = strtok($_SERVER["REQUEST_URI"],'?');
if ( !is_user_logged_in() &&
!in_array($url, array ( //using "in_array" because you can add mmultiple endpoints here
"/wp-json/cards",
))){
return new WP_Error( 'not-logged-in', 'API Requests to '.$url.' are only supported for authenticated requests', array( 'status' => 401 ) );
}
} );
这不是最好的解决方案,因为它将运行查询并过滤结果,但我一直在使用它,直到在执行查询之前发现阻止API访问的方法