通过 www.yourdomain.com/wp-json/ 查看所有 API 端口

禁用未登录用户获取 API

add_filter( 'rest_api_init', 'rest_only_for_authorized_users', 99 );
function rest_only_for_authorized_users($wp_rest_server){
    if ( !is_user_logged_in() ) {
        wp_die('Illegal operation!');
    }
}

禁用部分 API 端点

如:禁用 users 相关

add_filter( 'rest_endpoints', function( $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;
});

如:去除 oembed

foreach ($endpoints as $key=>$value){
    if(preg_match("/^(\/wp\/v2|\/oembed\/1.0|\/ft\/v1)/",$key)){
        unset( $endpoints[$key] );
    }
}
if ( isset( $endpoints['/'] ) ) {
    unset( $endpoints['/'] );
}

移除所有 API

add_action(' plugins_loaded ',function(){
    remove_filter(' rest_api_init ',' create_initial_rest_routes ');
});

登录用户不移除 oembed

add_filter( 'rest_endpoints', function( $endpoints ){
    foreach ($endpoints as $key=>$value){
        if(preg_match("/^(\/wp\/v2|\/oembed\/1.0|\/ft\/v1)/",$key) && defined(AUTH_KEY)){
            unset( $endpoints[$key] );
        }
    }
    if ( isset( $endpoints['/'] ) ) {
        unset( $endpoints['/'] );
    }
    return $endpoints;
});

注册添加新的 API 接口

function da_rest_hello_callback() {
  return 'hello new api';
}
function da_rest_register_route() {
  register_rest_route( 'myapi/', 'hello', [
    'methods'   => 'GET',
    'callback'  => 'da_rest_hello_callback'
  ] );
}
add_action( 'rest_api_init', 'da_rest_register_route');

通过访问 wp-json/myapi/hello ,则会出现hello new api。

原文链接:https://www.darlang.com/2018/05/wordpress-rest-api-interface-custom-control/

发表评论

电子邮件地址不会被公开。 必填项已用*标注