钩子文档

http_response

💡 云策文档标注

概述

http_response 是一个 WordPress 过滤器钩子,用于在成功的 HTTP API 响应返回前进行过滤。它允许开发者修改响应数据、参数或 URL,常用于自定义错误处理或内容调整。

关键要点

  • 过滤器名称:http_response
  • 触发时机:在 HTTP API 成功响应返回前立即执行
  • 参数:$response(HTTP 响应数组)、$parsed_args(HTTP 请求参数数组)、$url(请求 URL 字符串)
  • 返回值:过滤后的 HTTP 响应数组
  • 相关函数:WP_Http::_dispatch_request() 和 WP_Http::request()
  • 引入版本:WordPress 2.9.0

代码示例

/**
 * Return canned body content for invalid HTTP requests.
 *
 * In this example, "invalid" would be defined as any status code other than
 * 200, 301, or 302.
 *
 * @see WP_Http::request()
 *
 * @param array  $response The HTTP response.
 * @param array  $args     Request arguments. 
 * @param string $url      Request URL.
 *
 * @return array The filtered HTTP response.
*/
function wpdocs_invalid_request_response( $response, $args, $url ) {
	if ( ! in_array( $response['response']['code'], array( 200, 301, 302 ) ) ) {
		$response['body'] = __( 'No content found', 'yourtextdomain' );
	}
	return $response;
}
add_filter( 'http_response', 'wpdocs_invalid_request_response', 10, 3 );

📄 原文内容

Filters a successful HTTP API response immediately before the response is returned.

Parameters

$responsearray
HTTP response.
$parsed_argsarray
HTTP request arguments.
$urlstring
The request URL.

Source

return apply_filters( 'http_response', $response, $parsed_args, $url );

Changelog

Version Description
2.9.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    /**
     * Return canned body content for invalid HTTP requests.
     *
     * In this example, "invalid" would be defined as any status code other than
     * 200, 301, or 302.
     *
     * @see WP_Http::request()
     *
     * @param array  $response The HTTP response.
     * @param array  $args     Request arguments. 
     * @param string $url      Request URL.
     *
     * @return array The filtered HTTP response.
    */
    function wpdocs_invalid_request_response( $response, $args, $url ) {
    	if ( ! in_array( $response['response']['code'], array( 200, 301, 302 ) ) ) {
    		$response['body'] = __( 'No content found', 'yourtextdomain' );
    	}
    	return $response;
    }
    add_filter( 'http_response', 'wpdocs_invalid_request_response', 10, 3 );