2016-12-11 3 views
2

Как я могу дублировать по умолчанию wp rest api V2 endpoints? Я хотел бы сохранить неиспользуемые конечные точки и маршруты по умолчанию, но хотел бы использовать упрощенные ответы для моего приложения.Duplicate default WP REST API (v2) конечные точки

Wordpress v4.7

Мой код прямо сейчас:

function register_custom_routes() 
{ 
    $controller = new MY_REST_Posts_Controller; 
    $controller->register_routes(); 
} 

add_action('rest_api_init', 'register_custom_routes', 1); 

class MY_REST_Posts_Controller extends WP_REST_Controller { 
// this is a copy of default class WP_REST_Posts_Controller 
} 

Вызов http://localhost/wp/wp-json/ список моего пространства имен (/ myrest), также http://localhost/wp/wp-json/myrest/ дает мне:

{ 
    "namespace": "myrest", 
    "routes": { 
    "/myrest": { 
     "namespace": "myrest", 
     "methods": [ 
     "GET" 
     ], 
    ... 
    "/myrest/(?P<id>[\\d]+)": { 
     "namespace": "myrest", 
     "methods": [ 
     "GET", 
     "POST", 
     "PUT", 
     "PATCH", 
     "DELETE" 
     ], 
    ... 
} 

но когда я попробуйте перечислить сообщения с помощью http://localhost/wp/wp-json/myrest/posts (например, при вызове по маршруту api по умолчанию) не работает:

{ 
    "code": "rest_no_route", 
    "message": "No route was found matching the URL and request method", 
    "data": { 
    "status": 404 
    } 
} 

Мне нужна упрощенная версия ответа на получение сообщений для приложения для Android, но также вы хотите сохранить конечные точки отдыха и маршруты по умолчанию как есть.

+0

Вы нашли какие-либо решения? Я ищу то же самое. –

+0

Вы нашли решение? –

ответ

1

Вот решение. Я обернул код в плагин wp.

class WP_REST_custom_controller extends WP_REST_Controller { 

    // this is a copy of default class WP_REST_Posts_Controller 


    // Edited constructor for cutom namespace and endpoint url 
    /** 
    * Constructor. 
    * 
    * @since 4.7.0 
    * @access public 
    * 
    * @param string $post_type Post type. 
    */ 
    public function __construct() { 

     $this->post_type = 'post'; 
     $this->namespace = 'custom_namespace/v1'; 
     $obj = get_post_type_object($post_type); 
     $this->rest_base = ! empty($obj->rest_base) ? $obj->rest_base : $obj->name; 

     $this->resource_name = 'posts'; 

     $this->meta = new WP_REST_Post_Meta_Fields($this->post_type); 
    } 


    // this is a copy of default class WP_REST_Posts_Controller with necessary edits 

} 

// Function to register our new routes from the controller. 
function register_custom_rest_routes() { 
    $controller = new WP_REST_custom_controller(); 
    $controller->register_routes(); 
} 

add_action('rest_api_init', 'register_custom_rest_routes'); 
Смежные вопросы