admin管理员组

文章数量:1325408

I've created a plugin that adds a number of REST endpoints. And I am building a settings page that accesses those endpoints. Building UI with Backbone and the interfaces work well. However one of the settings pages needs to access data from one of the other endpoints. Following the example from / I tried:

 $request = new WP_REST_Request('GET', '/cloud_base/v1/aircraft_types');
 $rest_results = rest_do_request($request);

this fetches the JSON object prints it out and dies. The printed object appears to be correct, but why is it being printed? and why is it dieing?

I've created a plugin that adds a number of REST endpoints. And I am building a settings page that accesses those endpoints. Building UI with Backbone and the interfaces work well. However one of the settings pages needs to access data from one of the other endpoints. Following the example from https://developer.wordpress/rest-api/frequently-asked-questions/ I tried:

 $request = new WP_REST_Request('GET', '/cloud_base/v1/aircraft_types');
 $rest_results = rest_do_request($request);

this fetches the JSON object prints it out and dies. The printed object appears to be correct, but why is it being printed? and why is it dieing?

Share Improve this question asked Sep 10, 2020 at 17:22 dsjdsj 638 bronze badges 2
  • When access 'built-in' endpoint '/wp/v2/posts' I do not have this issue. – dsj Commented Sep 10, 2020 at 17:31
  • I found a brief comment on wordpress/core that wp_send_json($data) should not be used to return data from custom endpoints. (No explanation as to why.) Lacking any other documentation I have used the "wp_send_json" family extensively for my custom endpoints. Should be a note with the wp_send_json documentation to not do that. – dsj Commented Sep 11, 2020 at 19:03
Add a comment  | 

1 Answer 1

Reset to default 0

I done a bit of experimenting and in my custom endpoint i replaced :

wp_send_json($items);

with :

return new \WP_REST_Response ($items);

However I do not see how to extract my data from the WP_REST_Request object. I can see it is there with var_dump. But I can find no documentation as to how to access the data. This started because of a Question in the Wordpress REST handbook suggests you can access REST endpoints from PHP within a plugin. I though it would be better than directly accessing the DB. But I've wasted enough time.

本文标签: Accessing Custom REST endpoint with restdorequest()