Using WordPress ‘pre_http_request’ PHP filter

The ‘pre_http_request’ WordPress PHP filter allows you to modify or short-circuit an HTTP request in WordPress by using filters. You can return an array containing specific elements, a WP_Error instance, or false to avoid short-circuiting the response. Returning any other value may result in unexpected behavior.

Usage

$result = apply_filters('pre_http_request', $response, $parsed_args, $url);

Parameters

  • $response (false|array|WP_Error): A preemptive return value of an HTTP request. Default: false.
  • $parsed_args (array): HTTP request arguments.
  • $url (string): The request URL.

Examples

Bypass an HTTP request for a specific URL

function my_custom_pre_http_request($response, $parsed_args, $url) {
    if (strpos($url, 'example.com') !== false) {
        return array(
            'headers' => '',
            'body' => 'Request bypassed for example.com',
            'response' => array('code' => 200),
            'cookies' => '',
            'filename' => ''
        );
    }
    return $response;
}
add_filter('pre_http_request', 'my_custom_pre_http_request', 10, 3);

This code checks if the request URL contains ‘example.com’, and if so, it bypasses the actual HTTP request, returning a custom response.

Return a WP_Error for requests exceeding a specific timeout

function timeout_pre_http_request($response, $parsed_args, $url) {
    if ($parsed_args['timeout'] > 5) {
        return new WP_Error('timeout_error', 'Request timeout too high');
    }
    return $response;
}
add_filter('pre_http_request', 'timeout_pre_http_request', 10, 3);

This code checks if the request timeout is greater than 5 seconds, and if so, it returns a WP_Error instance with a custom message.

Block all HTTP requests

function block_all_http_requests($response, $parsed_args, $url) {
    return new WP_Error('all_requests_blocked', 'All HTTP requests are blocked');
}
add_filter('pre_http_request', 'block_all_http_requests');

This code blocks all HTTP requests by returning a WP_Error instance with a custom message.

Add a custom header to all HTTP requests

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

This code adds a custom header ‘X-Custom-Header’ with a value ‘MyValue’ to all HTTP requests.

Log all outgoing HTTP request URLs

function log_http_request_urls($response, $parsed_args, $url) {
    error_log('Request URL: ' . $url);
    return $response;
}
add_filter('pre_http_request', 'log_http_request_urls', 10, 3);

This code logs all outgoing HTTP request URLs using the PHP error_log() function.