Skip to main content
Robert Michalski

Increase http request timeout for plugins in WordPress

WordPress plugin http request timing out? #

WordPress sets a default timeout of 5 seconds for http requests. Many plugins call 3rd party APIs, sometimes those APIs are under heavy load or slower to respond because of maintenance or some other unknown reason. What happens then is that requests time out and are aborted before the server has responded, causing important actions to fail on your website.

One way to solve the problem is to set the timeout for all http requests, however that might affect other requests which already use longer timeouts, then you set it lower, which would cause them to be aborted prematurely.

A better solution is to first find out which URL is timing out, either by looking in the log files of PHP or checking through the source code of the plugin making the failing requests. When the URL that is timing out is known, use the http_request_timeout WordPress filter to increase the timeout, but only apply it for HTTP requests matching the failing URL.

add_filter('http_request_timeout', function($timeout, $url = '') {
    $start_with = 'https://example-api.url';
    
    //return is_string($url) && str_starts_with($url, $start_with) // PHP 8
    return is_string($url) && strncmp($url, $start_with, strlen($start_with)) === 0 // PHP 7 or older
        ? 15 // TODO: set appropriate timeout, WordPress default is 5 seconds
        : $timeout; // return unchanged timeout for other requests
}, 10, 2);

When setting a longer timeout, 30 or 60 seconds, PHP might stop processing before the HTTP request has had a chance to timeout. To prevent PHP processing from being aborted, the "PHP execution time limit" needs to be raised temporarily, just for the current request.

add_filter('http_request_timeout', function($timeout, $url = '') {
    $start_with = 'https://example-api.url';
    $timeout = is_string($url) && strncmp($url, $start_with, strlen($start_with)) === 0
        ? 15 // TODO: set appropriate timeout
        : $timeout;
    
    if ($timeout >= 60) { // TODO: set an appropriate time limit based on what the host allows
        @set_time_limit(60 + 10);   // raise PHP execution time limit, @ suppresses errors, to prevent PHP errors and allow the site to work,
                                    // albeit with possibility of timing out and aborting further PHP execution.
    } 
    
    return $timeout; 
}, 10, 2);