Using WordPress ‘http_response’ PHP filter

The http_response WordPress PHP Filter allows you to modify a successful HTTP API response before it is returned.

Usage

add_filter('http_response', 'your_function_name', 10, 3);
function your_function_name($response, $parsed_args, $url) {
    // Your custom code here

    return $response;
}

Parameters

  • $response (array) – The HTTP response.
  • $parsed_args (array) – The HTTP request arguments.
  • $url (string) – The request URL.

More information

See WordPress Developer Resources: http_response

Examples

Modify response headers

Add a custom header to the HTTP response.

add_filter('http_response', 'modify_response_headers', 10, 3);
function modify_response_headers($response, $parsed_args, $url) {
    $response['headers']['X-Custom-Header'] = 'CustomHeaderValue';
    return $response;
}

Log response data

Log the response data to a file for debugging purposes.

add_filter('http_response', 'log_response_data', 10, 3);
function log_response_data($response, $parsed_args, $url) {
    error_log(print_r($response, true));
    return $response;
}

Modify response body

Add a prefix to the response body.

add_filter('http_response', 'modify_response_body', 10, 3);
function modify_response_body($response, $parsed_args, $url) {
    $response['body'] = 'Custom Prefix: ' . $response['body'];
    return $response;
}

Change status code

Change the status code of the HTTP response.

add_filter('http_response', 'change_status_code', 10, 3);
function change_status_code($response, $parsed_args, $url) {
    $response['response']['code'] = 202;
    return $response;
}

Conditionally modify response

Modify the response only if the URL contains a specific string.

add_filter('http_response', 'conditionally_modify_response', 10, 3);
function conditionally_modify_response($response, $parsed_args, $url) {
    if (strpos($url, 'example.com') !== false) {
        $response['body'] = 'URL contains example.com';
    }
    return $response;
}

END