1

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",....}

0

1 Answer 1

3

The route should not include the /wp-json part, and there should be no trailing slash (/) at the end:

  • Wrong: /wp-json/wp/v2/pages/499/

  • Correct: /wp/v2/pages/499

So:

$request = new WP_REST_Request( 'GET', '/wp/v2/pages/499' );
2
  • My brain just skipped over the wp-json omission in the documentation: developer.wordpress.org/reference/classes/wp_rest_request
    – vlasits
    Commented Dec 6, 2018 at 17:04
  • 2
    It happens sometimes.. :) And (although you may already know), you can find the list of WordPress default routes here - and in your case, the route is here under the "Definition" section - /wp/v2/pages/<id>.
    – Sally CJ
    Commented Dec 6, 2018 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.