<?php
class Lionel_Category_List_Rest extends WP_REST_Controller {
/**
* The namespace.
*
* @var string
*/
protected $namespace;
/**
* Rest base for the current object.
*
* @var string
*/
protected $rest_base;
/**
* Category_List_Rest constructor.
*/
public function __construct() {
$this->namespace = 'categorylist/v2';
$this->rest_base = 'order';
}
/**
* Register the routes for the objects of the controller.
*/
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' ),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => array( $this, 'update_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( false ),
),
'schema' => null,
) );
}
/**
* Check permissions for the read.
*
* @param WP_REST_Request $request get data from request.
*
* @return bool|WP_Error
*/
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;
}
/**
* Check permissions for the update
*
* @param WP_REST_Request $request get data from request.
*
* @return bool|WP_Error
*/
public function update_item_permissions_check( $request ) {
if ( ! current_user_can( 'manage_options' ) ) {
return new WP_Error( 'rest_forbidden', esc_html__( 'You cannot update the category resource.' ), array( 'status' => $this->authorization_status_code() ) );
}
return true;
}
/**
* Grabs all the category list.
*
* @param WP_REST_Request $request get data from request.
*
* @return mixed|WP_REST_Response
*/
public function get_items( $request ) {
$cat_order = get_option( 'category_order' );
$data = get_categories();
$res = [];
if ( $cat_order ) {
$index = 0;
foreach ( $cat_order as $cat ) {
$temp = [];
$temp['name'] = get_cat_name( $cat );
$temp['id'] = $cat;
$temp['order'] = $index;
$res[] = $temp;
$index++;
}
} elseif ( ! empty( $data ) ) {
$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 );
}
/**
* Update category order
*
* @param WP_REST_Request $request get data from request.
*
* @return mixed|WP_Error|WP_REST_Response
*/
public function update_item( $request ) {
$data = [];
if ( ! isset( $request['order'] ) ) {
return new WP_Error( 'invalid_data', __( 'Cannot update category order.' ), array( 'status' => 400 ) );
}
$res = update_option( 'category_order', $request['order'] );
if ( $res ) {
$data['msg'] = __( 'Category order updated', '' );
} else {
return new WP_Error( 'cant update', __( 'Please provide proper data' ), array( 'status' => 400 ) );
}
return rest_ensure_response( $data );
}
/**
* Sets up the proper HTTP status code for authorization.
*
* @return int
*/
public function authorization_status_code() {
$status = 401;
if ( is_user_logged_in() ) {
$status = 403;
}
return $status;
}
}
/**
* Function to register our new routes from the controller.
*/
function register_cat_list_controller() {
$controller = new Lionel_Category_List_Rest();
$controller->register_routes();
}
add_action( 'rest_api_init', 'register_cat_list_controller' );?>
Ví dụ 2: Lấy ví dụ ở trên trang hướng dẫn :)
The following is a “starter” custom route:
<?php
class Slug_Custom_Route extends WP_REST_Controller {
/**
* Register the routes for the objects of the controller.
*/
public function abc() {
return 'aaaaaaaaaaaaaa';
}
public function register_routes() {
$version = '1';
$namespace = 'vendor/v' . $version;
$base = 'route';
register_rest_route($namespace, '/' . $base, array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array($this, 'get_items'),
'permission_callback' => array($this, 'get_items_permissions_check'),
'args' => array(
),
),
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array($this, 'create_item'),
'permission_callback' => array($this, 'create_item_permissions_check'),
'args' => $this->get_endpoint_args_for_item_schema(true),
),
));
register_rest_route($namespace, '/' . $base . '/(?P<id>[\d]+)', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array($this, 'get_item'),
'permission_callback' => array($this, 'get_item_permissions_check'),
'args' => array(
'context' => array(
'default' => 'view',
),
),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array($this, 'update_item'),
'permission_callback' => array($this, 'update_item_permissions_check'),
'args' => $this->get_endpoint_args_for_item_schema(false),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => array($this, 'delete_item'),
'permission_callback' => array($this, 'delete_item_permissions_check'),
'args' => array(
'force' => array(
'default' => false,
),
),
),
));
register_rest_route($namespace, '/' . $base . '/schema', array(
'methods' => WP_REST_Server::READABLE,
'callback' => array($this, 'get_public_item_schema'),
));
}
/**
* Get a collection of items
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|WP_REST_Response
*/
public function get_items($request) {
$items = array(); //do a query, call another class, etc
$data = array();
foreach ($items as $item) {
$itemdata = $this->prepare_item_for_response($item, $request);
$data[] = $this->prepare_response_for_collection($itemdata);
}
return new WP_REST_Response($data, 200);
}
/**
* Get one item from the collection
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|WP_REST_Response
*/
public function get_item($request) {
//get parameters from request
$params = $request->get_params();
$item = array(); //do a query, call another class, etc
$data = $this->prepare_item_for_response($item, $request);
//return a response or error based on some conditional
if (1 == 1) {
return new WP_REST_Response($data, 200);
} else {
return new WP_Error('code', __('message', 'text-domain'));
}
}
/**
* Create one item from the collection
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|WP_REST_Response
*/
public function create_item($request) {
$item = $this->prepare_item_for_database($request);
if (function_exists('slug_some_function_to_create_item')) {
$data = slug_some_function_to_create_item($item);
if (is_array($data)) {
return new WP_REST_Response($data, 200);
}
}
return new WP_Error('cant-create', __('message', 'text-domain'), array('status' => 500));
}
/**
* Update one item from the collection
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|WP_REST_Response
*/
public function update_item($request) {
$item = $this->prepare_item_for_database($request);
if (function_exists('slug_some_function_to_update_item')) {
$data = slug_some_function_to_update_item($item);
if (is_array($data)) {
return new WP_REST_Response($data, 200);
}
}
return new WP_Error('cant-update', __('message', 'text-domain'), array('status' => 500));
}
/**
* Delete one item from the collection
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|WP_REST_Response
*/
public function delete_item($request) {
$item = $this->prepare_item_for_database($request);
if (function_exists('slug_some_function_to_delete_item')) {
$deleted = slug_some_function_to_delete_item($item);
if ($deleted) {
return new WP_REST_Response(true, 200);
}
}
return new WP_Error('cant-delete', __('message', 'text-domain'), array('status' => 500));
}
/**
* Check if a given request has access to get items
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|bool
*/
public function get_items_permissions_check($request) {
//return true; <--use to make readable by all
return current_user_can('edit_something');
}
/**
* Check if a given request has access to get a specific item
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|bool
*/
public function get_item_permissions_check($request) {
return $this->get_items_permissions_check($request);
}
/**
* Check if a given request has access to create items
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|bool
*/
public function create_item_permissions_check($request) {
return current_user_can('edit_something');
}
/**
* Check if a given request has access to update a specific item
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|bool
*/
public function update_item_permissions_check($request) {
return $this->create_item_permissions_check($request);
}
/**
* Check if a given request has access to delete a specific item
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|bool
*/
public function delete_item_permissions_check($request) {
return $this->create_item_permissions_check($request);
}
/**
* Prepare the item for create or update operation
*
* @param WP_REST_Request $request Request object
* @return WP_Error|object $prepared_item
*/
protected function prepare_item_for_database($request) {
return array();
}
/**
* Prepare the item for the REST response
*
* @param mixed $item WordPress representation of the item.
* @param WP_REST_Request $request Request object.
* @return mixed
*/
public function prepare_item_for_response($item, $request) {
return array();
}
/**
* Get the query params for collections
*
* @return array
*/
public function get_collection_params() {
return array(
'page' => array(
'description' => 'Current page of the collection.',
'type' => 'integer',
'default' => 1,
'sanitize_callback' => 'absint',
),
'per_page' => array(
'description' => 'Maximum number of items to be returned in result set.',
'type' => 'integer',
'default' => 10,
'sanitize_callback' => 'absint',
),
'search' => array(
'description' => 'Limit results to those matching a string.',
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
),
);
}
}
function register_cat_list_controller() {
$vendor = new Slug_Custom_Route();
$vendor->register_routes();
}
add_action('rest_api_init', 'register_cat_list_controller');
?>