rest_ensure_response

函数
rest_ensure_response ( $response )
参数
  • (WP_REST_Response|WP_Error|WP_HTTP_Response|mixed) $response Response to check.
    Required:
返回值
  • (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.
定义位置
相关方法
rest_ensure_requestrest_filter_response_fieldsrest_convert_error_to_responseget_oembed_response_datarest_filter_response_by_context
引入
4.4.0
弃用
-

rest_ensure_response: 这个函数用来确保REST API返回的数据是正确的格式。它接收一个数据对象,并返回一个包含数据的WP_REST_Response对象,以及相应的头信息和状态代码。

确保REST响应是一个响应对象(为了一致性)。

这实现了WP_REST_Response,允许使用`set_status`/`header`/etc而不需要重复检查对象。也将允许WP_Error表示错误响应,所以用户应该立即检查这个值。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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 );
}
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 ); }
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 );
}

常见问题

FAQs
查看更多 >