如何复制默认的wp 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
}
}
我需要简化版本的get帖子响应的android应用,但也希望保持默认的休息端点和路由。
发布于 2017-10-06 13:44:23
这是解决办法。我用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');
https://stackoverflow.com/questions/41092111
复制相似问题