1 2 3 4 5 6 |
add_filter( 'rest_endpoints', 'show_default_endpoints' ); function show_default_endpoints( $endpoints ) { var_export( array_keys( $endpoints ) ); die; } |
您可以通过向rest_authentication_errors过滤器添加is_user_logged_in检查来要求对所有REST API请求进行身份验证:
1 2 3 4 5 6 7 8 9 |
add_filter( 'rest_authentication_errors', function( $result ) { if ( ! empty( $result ) ) { return $result; } if ( ! is_user_logged_in() ) { return new WP_Error( 'rest_not_logged_in', 'You are not currently logged in.', array( 'status' => 401 ) ); } return $result; }); |
1 2 3 4 5 6 7 8 9 10 11 |
/** * Disables WordPress Rest API for external requests */ function restrict_rest_api_to_localhost() { $whitelist = array('127.0.0.1', "::1"); if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){ die('REST API is disabled.'); } } add_action( 'rest_api_init', 'restrict_rest_api_to_localhost', 1 ); |
返回一个空数组,所有路由都消失了。
1 2 3 4 5 |
add_filter( 'rest_endpoints', 'remove_default_endpoints' ); function remove_default_endpoints( $endpoints ) { return array( ); } |
如果你自定了API路由,那上面的操作过于果断,我们要处理一下,把你的自定义路由保留下来:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
add_filter( 'rest_endpoints', 'remove_default_endpoints_smarter' ); function remove_default_endpoints_smarter( $endpoints ) { $prefix = 'your_custom_endpoint_prefix'; foreach ( $endpoints as $endpoint => $details ) { if ( !fnmatch( '/' . $prefix . '/*', $endpoint, FNM_CASEFOLD ) ) { unset( $endpoints[$endpoint] ); } } return $endpoints; } |
只需使用自定义前缀跳过并将其保留在数组中。别忘了返回数组。
自定义路由
1 2 3 4 5 |
add_filter( 'rest_url_prefix', 'rest_url_prefix' ); function rest_url_prefix( ) { return 'api'; } |
使用上面的过滤器,您的路由将是mysite.com/api/,打开旧的mysite.com/wp-json/ URL将产生404错误。
确保在自定义路由路径中包含版本号,因为WP不会自动添加前缀。版本号前缀可确保在未来发生变化时不会破坏使用旧路径的客户端。只需在调用register_rest_route()时包含版本前缀,以获得类似mysite.com/api/v1/的内容,并将所有路由路径保留在“v1”之后,以便后续可以使用“v2”等。
原文连接
的情况下转载,若非则不得使用我方内容。