I'm running WordPress 4.9.8 with a Genesis theme (probably irrelevant, but...). I'd like to write some JSON pulled from the REST API directly to a script tag when a page is built (rather than hitting the API from an AJAX call) for snappier performance.
Fortunately, WP offers WP_REST_Request for situations like this. So I wrote some code that looks like this:
functions.php
add_action('wp_head', 'write_json_to_script_tag');
function write_json_to_script_tag(){
$request = new WP_REST_Request( 'GET', '/wp-json/wp/v2/pages/499/');
$response = rest_do_request( $request );
var_dump($response);
$server = rest_get_server();
$data = $server->response_to_data( $response, false );
$json = wp_json_encode( $data );
echo '<script type="text/javascript"> var the_json = ' . $json . '</script>';
}
When I hit https://example.com/wp-json/wp/v2/pages/499 in a browser it produces exactly the json I expect. When I curl that url I get the same result. But my server code returns {code: "rest_no_route", message: "No route was found matching the URL and request method",....}