Request to REST endpoint works fine in browser and curl, but fails from WP_REST_Request

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

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

Share Improve this question asked Dec 6, 2018 at 16:22 vlasitsvlasits 1357 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 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' );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749123021a316559.html

最新回复(0)