docs-v2 icon indicating copy to clipboard operation
docs-v2 copied to clipboard

Add documentation on how to run requests internally

Open basschoen opened this issue 9 years ago • 6 comments

For server side JavaScript rendering I want to call some of the API functions in PHP code. What is the best way to do this? For example, how can I fetch all the categories

xx/wp-json/wp/v2/categories

without a cURL request, but with normal PHP code within my WordPress plugin. Thanks!

basschoen avatar Feb 25 '16 19:02 basschoen

$r = wp_remote_get( 'http://whatever.com/wp/v2/categories' ); You should find Tom McFarlin's series on the WordPress HTTP API.

https://codex.wordpress.org/Function_Reference/wp_remote_get

Shelob9 avatar Feb 25 '16 20:02 Shelob9

Sorry, didn't mean to close.

Shelob9 avatar Feb 25 '16 20:02 Shelob9

You can internally run requests quite easily:

$request = new WP_REST_Request( 'GET', '/wp/v2/categories' );
$server = rest_get_server();
$response = $server->dispatch( $request );

This is way cheaper than a cURL request, but note that this won't do embedding or anything for you.

We should document how to run these internal requests :)

rmccue avatar Feb 26 '16 02:02 rmccue

Thanks @rmccue, where does this rest_get_server() function comes from?

basschoen avatar Feb 26 '16 07:02 basschoen

Added in core recently per this ticket.

rmccue avatar Feb 26 '16 13:02 rmccue

Brand new! Thanks, will work with this.

basschoen avatar Feb 26 '16 13:02 basschoen