2. Write API READABLE Category Order (có permission_callback)
Previous1. Write API READABLE Category Order (chưa có permission_callback)Next3. Write API EDITABLE Category Order (không có permission_callback)
Last updated
Last updated
<?php
class Lionel_Category_List_Rest extends WP_REST_Controller {
protected $namespace;
protected $rest_base;
public function __construct() {
$this->namespace = 'categorylist/v2';
$this->rest_base = 'order';
}
public function register_routes() {
register_rest_route($this->namespace, '/' . $this->rest_base, array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array($this, 'get_items'),
'permission_callback' => array($this, 'get_items_permissions_check'),
),
'schema' => null,
));
}
public function get_items($request) {
$data = get_categories();
$res = [];
$index = 0;
foreach ($data as $list) {
if ('category' === $list->taxonomy) {
$temp = [];
$temp['name'] = $list->name;
$temp['id'] = $list->term_id;
$temp['order'] = $index;
$res[] = $temp;
$index++;
}
}
// Return all of our comment response data.
return rest_ensure_response($res);
}
public function get_items_permissions_check($request) {
if (!current_user_can('read')) {
return new WP_Error('rest_forbidden', esc_html__('You cannot view the category resource.'), array('status' => $this->authorization_status_code()));
}
return true;
}
public function authorization_status_code() {
$status = 401;
if (is_user_logged_in()) {
$status = 403;
}
return $status;
}
}
function register_cat_list_controller() {
$controller = new Lionel_Category_List_Rest();
$controller->register_routes();
}
add_action('rest_api_init', 'register_cat_list_controller');
?>