Last active
May 30, 2020 05:03
-
-
Save joehoyle/e7321570525af6daeae2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: