[API] Một ví dụ đăng ký một route và trả về giá trị (ok)

Ví dụ 1: không có permission_callback

<?php
/**
 * Grab latest post title by an author!
 *
 * @param array $data Options for the function.
 * @return string|null Post title for the latest,
 * or null if none.
 */
function my_awesome_func($data) {
  $posts = get_posts(
    array(
      'author' => $data['id'],
    )
  );
  if (empty($posts)) {
    return null;
  }
  return $posts[0]->post_title;
}
add_action('rest_api_init', function () {
  register_rest_route('myplugin/v1', '/author/(?P<id>\d+)', array(
    'methods'  => 'GET',
    'callback' => 'my_awesome_func',
  ));
});
?>

Ví dụ 2: Có permission_callback

<?php
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');
    },
  ));
});
function my_awesome_func($data) {
  $posts = get_posts(array(
    'author' => $data['id'],
  ));
  if (empty($posts)) {
    return new WP_Error('no_author', 'Invalid author', array('status' => 404));
  }
  return $posts[0]->post_title;
}
?>

Tìm hiểu thêm function current_user_can()

Hàm này cũng chấp nhận ID của một đối tượng để kiểm tra xem khả năng có phải là một khả năng meta hay không. Các khả năng meta như edit_post và edit_user là các khả năng được sử dụng bởi hàm map_meta_cap () để ánh xạ tới các khả năng nguyên thủy mà người dùng hoặc vai trò có, chẳng hạn như edit_posts và edit_others_posts.

Last updated