<?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')
),
'schema' => null,
));
}
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);
}
}
function register_cat_list_controller() {
$controller = new Lionel_Category_List_Rest();
$controller->register_routes();
}
add_action('rest_api_init', 'register_cat_list_controller');
?>