Internal Requests to the WordPress REST API

The WordPress REST API can be called not only via HTTP from an external application or JavaScript, but also directly from PHP code inside WordPress.

Such a request is handled by the regular REST API, but it does not require a separate call to the server via a URL.

Why it’s needed

To get posts inside WordPress, you usually use WP_Query. But the result of its operation differs from the data returned by the REST API.

An internal REST request is useful when PHP and JavaScript code need data in the same format. For example, PHP can fetch initial data and immediately pass it to the application when the page loads.

This allows:

  • not to perform an additional HTTP request after the page loads.
  • to display the data immediately without an intermediate loading indicator.
  • not to load WordPress and plugins a second time for a single request.

How to perform an internal REST request

Create an WP_REST_Request object, pass it the HTTP method and route, then execute the request using rest_do_request():

$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );
$request->set_query_params( [
	'per_page' => 12,
] );

$resp = rest_do_request( $request );
$data = rest_get_server()->response_to_data( $resp, false );
$json = wp_json_encode( $data );

The set_query_params() method sets the parameters that, in a regular HTTP request, are passed in the URL string. REST API parameter names can differ from the arguments of WP_Query. For example, instead of post_status, status is used.

The rest_do_request() function sends the REST request to the WordPress REST server and returns the response object.

The response_to_data() method converts the response into an array. The second argument determines whether to add embedded resources from _embedded:

  • false - do not add;
  • true - add if the route supports embedding.

To get JSON, pass the array to wp_json_encode().

Permission checks

The internal call does not go through external HTTP authentication, but the REST API still executes permission_callback of the route in the current WordPress context. Therefore, before accessing restricted data or performing changes, explicitly check the user permissions.