Skip to content

Instantly share code, notes, and snippets.

@joehoyle
Last active May 30, 2020 05:03
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joehoyle/e7321570525af6daeae2 to your computer and use it in GitHub Desktop.
Save joehoyle/e7321570525af6daeae2 to your computer and use it in GitHub Desktop.
<?php
/**
* Make an internal REST request
*
* @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
* @param $request_or_method WP_REST_Request|string A WP_REST_Request object or a request method
* @param $path (optional) if the path is not specific in the rest request, specify it here
* @param $data (optional) option data for the request.
* @return WP_Error|mixed
*/
function rest_internal_request( $request_or_method, $path = null, $data = array() ) {
/** @var WP_REST_Server $wp_rest_server */
global $wp_rest_server;
if ( empty( $wp_rest_server ) ) {
/**
* Filter the REST Server Class.
*
* This filter allows you to adjust the server class used by the API, using a
* different class to handle requests.
*
* @since 4.4.0
*
* @param string $class_name The name of the server class. Default 'WP_REST_Server'.
*/
$wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' );
$wp_rest_server = new $wp_rest_server_class;
/**
* Fires when preparing to serve an API request.
*
* Endpoint objects should be created and register their hooks on this action rather
* than another action to ensure they're only loaded when needed.
*
* @since 4.4.0
*
* @param WP_REST_Server $wp_rest_server Server object.
*/
do_action( 'rest_api_init', $wp_rest_server );
}
if ( is_a( $request_or_method, 'WP_REST_Request' ) ) {
$request = $request_or_method;
} else {
$request = new WP_REST_Request( $request_or_method, $path );
foreach ( $data as $k => $v ) {
$request->set_param( $k, $v );
}
}
$result = $wp_rest_server->dispatch( $request );
if ( $result->is_error() ) {
return $result->as_error();
}
$result = $wp_rest_server->response_to_data( $result, ! empty( $data['_embed'] ) );
return $result;
}
@joehoyle
Copy link
Author

Using the REST API internally within PHP can be useful for a number of cases. For example, pre-loading REST API data in the body of a document so there's no need to make initial API calls:

wp_localize_script( 'myScript', 'Tags', array(
    'tags' => rest_internal_request( 'GET', '/wp/v2/terms/tags', array( 'per_page' => 20 ) ),
) );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment