函数文档

wp_remote_retrieve_response_code()

💡 云策文档标注

概述

wp_remote_retrieve_response_code() 函数用于从 HTTP 响应中提取状态码。它接受一个数组或 WP_Error 对象作为参数,返回整数状态码或空字符串。

关键要点

  • 函数从原始响应中仅提取 HTTP 状态码,如 200、404 等。
  • 参数 $response 必须是数组或 WP_Error 对象,否则返回空字符串。
  • 内部检查包括 is_wp_error() 和响应数组的有效性。
  • 返回值类型为整数或字符串(空字符串表示无效参数)。

代码示例

$response = wp_remote_get( 'http://www.foo.com/file.txt' );
$response_code = wp_remote_retrieve_response_code( $response );

注意事项

  • 确保 $response 参数来自 wp_remote_get() 或类似函数,以避免错误。
  • 函数在 WordPress 2.7.0 版本引入,兼容性良好。
  • 相关函数包括 is_wp_error() 和多个使用此函数的 WordPress 核心类。

📄 原文内容

Retrieves only the response code from the raw response.

Description

Will return an empty string if incorrect parameter value is given.

Parameters

$responsearray|WP_Errorrequired
HTTP response.

Return

int|string The response code as an integer. Empty string if incorrect parameter given.

Source

function wp_remote_retrieve_response_code( $response ) {
	if ( is_wp_error( $response ) || ! isset( $response['response'] ) || ! is_array( $response['response'] ) ) {
		return '';
	}

	return $response['response']['code'];
}

Changelog

Version Description
2.7.0 Introduced.

User Contributed Notes