[API] Một ví dụ về phân quyền gọi lại Permissions Callback (ok)

https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/

<?php
/**
 * This is our callback function that embeds our resource in a WP_REST_Response
 */
function prefix_get_private_data() {
  // rest_ensure_response() wraps the data we want to return into a WP_REST_Response, and ensures it will be properly returned.
  return rest_ensure_response('This is private data.');
}
/**
 * This is our callback function that embeds our resource in a WP_REST_Response
 */
function prefix_get_private_data_permissions_check() {
  // Restrict endpoint to only users who have the edit_posts capability.
  if (!current_user_can('edit_posts')) {
    return new WP_Error('rest_forbidden', esc_html__('OMG you can not view private data.', 'my-text-domain'), array('status' => 401));
  }
  // This is a black-listing approach. You could alternatively do this via white-listing, by returning false here and changing the permissions check.
  return true;
}
/**
 * This function is where we register our routes for our example endpoint.
 */
function prefix_register_example_routes() {
  // register_rest_route() handles more arguments but we are going to stick to the basics for now.
  register_rest_route('my-plugin/v1', '/private-data', array(
    // By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended.
    'methods'             => WP_REST_Server::READABLE,
    // Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class.
    'callback'            => 'prefix_get_private_data',
    // 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' => 'prefix_get_private_data_permissions_check',
  ));
}
add_action('rest_api_init', 'prefix_register_example_routes');
?>

Last updated