rest_ensure_response

Ensures a REST response is a response object (for consistency).

Description

(WP_REST_Response|mixed) rest_ensure_response( (WP_Error|WP_HTTP_Response|mixed) $response ); 

This implements WP_HTTP_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.

Returns (WP_REST_Response|mixed)

If response generated an error, WP_Error, if response is already an instance, WP_HTTP_Response, otherwise returns a new WP_REST_Response instance.

Parameters (1)

0. $response (WP_Error|WP_HTTP_Response|mixed)
Response to check.

Usage

  1. if ( !function_exists( 'rest_ensure_response' ) ) { 
  2. require_once ABSPATH . WPINC . '/rest-api.php'; 
  3.  
  4. // Response to check. 
  5. $response = null; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = rest_ensure_response($response); 
  9.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/rest-api.php  
  1. function rest_ensure_response( $response ) { 
  2. if ( is_wp_error( $response ) ) { 
  3. return $response; 
  4.  
  5. if ( $response instanceof WP_HTTP_Response ) { 
  6. return $response; 
  7.  
  8. return new WP_REST_Response( $response );