社区首页 >问答首页 >重复默认WP REST (v2)端点

重复默认WP REST (v2)端点
EN

Stack Overflow用户
提问于 2016-12-11 15:01:44
回答 1查看 820关注 0票数 2

如何复制默认的wp V2端点?我想保持默认端点和路由不变,但我想使用简化的响应我的应用程序。

Wordpress v4.7

我现在的密码是:

代码语言:javascript
代码运行次数:0
复制
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/也提供给我:

代码语言:javascript
代码运行次数:0
复制
{
  "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路由调用)时,它不起作用:

代码语言:javascript
代码运行次数:0
复制
{
  "code": "rest_no_route",
  "message": "No route was found matching the URL and request method",
  "data": {
    "status": 404
  }
}

我需要简化版本的get帖子响应的android应用,但也希望保持默认的休息端点和路由。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-06 13:44:23

这是解决办法。我用wp插件包装了代码。

代码语言:javascript
代码运行次数:0
复制
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');
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41092111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文