rest_ensure_response()
Ensures a REST response is a response object (for consistency).
This implements WP_REST_Response, allowing usage of set_status/header/etc without needing to double-check the object. Will also allow WP_Error to indicate error responses, so users should immediately check for this value.
Uses: WP_REST_Response()
No Hooks.
Return
WP_REST_Response|WP_Error
. If response generated an error, WP_Error, if response is already an instance, WP_REST_Response, otherwise returns a new WP_REST_Response instance.
Usage
rest_ensure_response( $response );
- $response(WP_REST_Response|WP_Error|WP_HTTP_Response|mixed) (required)
- Response to check.
Examples
#1 Getting the posts of the specified author
In WordPress, there are default methods for this purpose, but let's create our own simple version for example:
// registers the route add_action( 'rest_api_init', function () { register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', ) ); } ); // Processes the request function my_awesome_func( WP_REST_Request $request ) { $posts = get_posts( [ 'author' => (int) $request['id'], ] ); if ( empty( $posts ) ) { return new WP_Error('no_author_posts', 'No posts found', array( 'status' => 404 ); } $response = rest_ensure_response( $posts ); $response->set_status( 201 ); $response->set_headers( [ //'CONTENT_TYPE' => 'application/x-www-form-urlencoded', //'CONTENT_LENGTH' => 105, 'X_REAL_IP' => '54.15.124.126', ] ); //$this->set_data( $data ); return $response; }
Changelog
Since 4.4.0 | Introduced. |
rest_ensure_response() rest ensure response code WP 6.1.1
function rest_ensure_response( $response ) { if ( is_wp_error( $response ) ) { return $response; } if ( $response instanceof WP_REST_Response ) { return $response; } // While WP_HTTP_Response is the base class of WP_REST_Response, it doesn't provide // all the required methods used in WP_REST_Server::dispatch(). if ( $response instanceof WP_HTTP_Response ) { return new WP_REST_Response( $response->get_data(), $response->get_status(), $response->get_headers() ); } return new WP_REST_Response( $response ); }