Custom Endpoints not working

时间:2019-06-25 作者:Alex Knopp

第一次创建自定义端点。我将从另一个wordpres安装的站点获取帖子。

这是我的插件代码。

/**
* Add endpoint URLs
*/    
public function __construct(){

    add_action(\'rest_api_init\', function(){

        // Get submissions from the database
        register_rest_route(\'knpv-get\',\'get-submissions\', array(
            \'methods\'=>\'GET\', 
            \'callback\' => \'get_submissions_by_email\'
            )
        );

    });

}

/**
* Get submisions by email endpoint callback
*/
public function get_submissions_by_email($data){

    $posts = get_posts();
    return $posts;

}
但当我在浏览器中查看url(domain/wp-json/knpv-get/)时,我得到的只是:

    {"namespace":"knpv-get","routes":{"\\/knpv-get":{"namespace":"knpv-get","methods":["GET"],"endpoints":[{"methods":["GET"],"args":{"namespace":{"required":false,"default":"knpv-get"},"context":{"required":false,"default":"view"}}}],"_links":{"self":"http:\\/\\/knoppysdev.com\\/vendor-portal\\/wp-json\\/knpv-get"}},"\\/knpv-get\\/get-submissions":{"namespace":"knpv-get","methods":["GET"],"endpoints":[{"methods":["GET"],"args":[]}],"_links":{"self":"http:\\/\\/knoppysdev.com\\/vendor-portal\\/wp-json\\/knpv-get\\/get-submissions"}}},"_links":{"up":[{"href":"http:\\/\\/knoppysdev.com\\/vendor-portal\\/wp-json\\/"}]}}
我遗漏了什么,它不应该返回一些帖子吗。这是一个新的安装,所以只有Hello World可以返回。

1 个回复
最合适的回答,由SO网友:Jacob Peattie 整理而成

你走错了路。的前两个参数register_rest_route() ar名称空间和路由。REST API端点的URL为:

(your domain) + \'/wp-json/\' + (namespace) + \'/\' + (route)
因此,指向端点的完整URL是:

http://domain.com/wp-json/knpv-get/get-submissions
但您正在尝试查看:

http://domain.com/wp-json/knpv-get
它不会从回调函数返回响应。但是,如果仔细查看结果,您将看到它在knpv-get 命名空间:

{
  "namespace": "knpv-get",
  "routes": {
    "\\/knpv-get": {
      "namespace": "knpv-get",
      "methods": [
        "GET"
      ],
      "endpoints": [
        {
          "methods": [
            "GET"
          ],
          "args": {
            "namespace": {
              "required": false,
              "default": "knpv-get"
            },
            "context": {
              "required": false,
              "default": "view"
            }
          }
        }
      ],
      "_links": {
        "self": "http:\\/\\/knoppysdev.com\\/vendor-portal\\/wp-json\\/knpv-get"
      }
    },
    "\\/knpv-get\\/get-submissions": {
      "namespace": "knpv-get",
      "methods": [
        "GET"
      ],
      "endpoints": [
        {
          "methods": [
            "GET"
          ],
          "args": [

          ]
        }
      ],
      "_links": {
        "self": "http:\\/\\/knoppysdev.com\\/vendor-portal\\/wp-json\\/knpv-get\\/get-submissions"
      }
    }
  },
  "_links": {
    "up": [
      {
        "href": "http:\\/\\/knoppysdev.com\\/vendor-portal\\/wp-json\\/"
      }
    ]
  }
}