rest_ensure_response() WordPress Function

The rest_ensure_response() function is used to make sure that a WordPress REST API response is a valid response object. This function can be used to wrap a WordPress REST API response in an array, or it can be used to wrap a WordPress REST API response in an object.

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

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


Description

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.


Top ↑

Parameters

$response

(WP_REST_Response|WP_Error|WP_HTTP_Response|mixed)(Required)Response to check.


Top ↑

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.


Top ↑

Source

File: wp-includes/rest-api.php

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 );
}


Top ↑

Changelog

Changelog
VersionDescription
4.4.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More