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
檢視更多 >