如何复制默认的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 :(得分: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');