Using WordPress ‘rest_ensure_response()’ PHP function

The rest_ensure_response() WordPress PHP function ensures a REST response is a response object for consistency.

Usage

$response = rest_ensure_response($input_response);

Parameters

  • $response (WP_REST_Response|WP_Error|WP_HTTP_Response|mixed): The response to check.

More information

See WordPress Developer Resources: rest_ensure_response()

Examples

Checking a valid WP_REST_Response

In this example, we are creating a valid WP_REST_Response and checking if it is a response object.

$data = array('key' => 'value');
$rest_response = new WP_REST_Response($data);
$checked_response = rest_ensure_response($rest_response);

Checking an invalid response

In this example, we are creating an invalid response and checking if it is a response object.

$invalid_response = "Not a valid response";
$checked_response = rest_ensure_response($invalid_response);

Handling a WP_Error

In this example, we create a WP_Error and check if it’s a response object.

$error_response = new WP_Error('error_code', 'Error Message');
$checked_response = rest_ensure_response($error_response);

Working with WP_HTTP_Response

In this example, we create a WP_HTTP_Response and check if it’s a response object.

$http_response = new WP_HTTP_Response();
$http_response->set_data(array('key' => 'value'));
$checked_response = rest_ensure_response($http_response);

Checking an array

In this example, we check an array and ensure it’s a response object.

$array_data = array('key' => 'value');
$checked_response = rest_ensure_response($array_data);