对于那些在2021读到这篇文章的人来说@Sisir
WordPress: 版本5.7.2PHP: 版本7.4
你有没有试过Permission Callback ?
根据WP的以下2个nice来源REST API Handbook:
REST API Handbook / Extending the REST API / Routes and Endpoints
REST API Handbook / Extending the REST API / Adding Custom Endpoints
/**
* Permission Callback function:
* \'ypp\' is the Prefix I chose (ypp = Your Private Page)
*/
function ypp_get_private_data_permissions_check() {
/**
* Restrict endpoint to allowed IPs (white listing approach)
*/
$allowed_ips = array( \'127.0.0.1\' );
$request_server = $_SERVER[\'REMOTE_ADDR\'];
if( ! in_array( $request_server, $allowed_ips ) )
return new WP_Error( \'rest_forbidden\', esc_html__( \'Access denied from your IP address.\', \'my-text-domain\' ), array( \'status\' => 401 ) );
return true;
};
add_action(\'rest_api_init\', function() {
/**
* Register here your custom routes for your CRUD functions
*/
register_rest_route( \'your_private_page/v1\', \'/data\', array(
array(
\'methods\' => WP_REST_Server::READABLE,
\'callback\' => \'get_your_data\', // <-- your main callback function
// Always allow GET, for example
\'permission_callback\' => \'__return_true\' // <-- to leave it open
),
array(
\'methods\' => WP_REST_Server::CREATABLE,
\'callback\' => \'insert_your_data\', // <-- your main callback function
// Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint.
\'permission_callback\' => \'ypp_get_private_data_permissions_check\',
),
array(
\'methods\' => WP_REST_Server::EDITABLE,
\'callback\' => \'update_your_data\', // <-- your main callback function
// Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint.
\'permission_callback\' => \'ypp_get_private_data_permissions_check\',
),
));
});
Note:不再需要插件。这个
WP REST API 已合并到WordPress核心。