Skip to content

Instantly share code, notes, and snippets.

@bookchiq
Created September 1, 2023 17:02
Show Gist options
  • Save bookchiq/6da910996077ee2bb694a04c35028711 to your computer and use it in GitHub Desktop.
Save bookchiq/6da910996077ee2bb694a04c35028711 to your computer and use it in GitHub Desktop.
A wrapper for WordPress's wp_remote_request() that retries after common cURL errors with exponential backoff
<?php
/**
* Wrapper for wp_remote_request() with retry logic.
*
* @param string $url The URL to make the request to.
* @param array $args Optional. An array of HTTP request arguments.
* @param array $retry_curl_codes Optional. An array of cURL error codes to trigger a retry.
* @param int $max_retries Optional. The maximum number of retries.
* @return array|\WP_Error The response or WP_Error on failure.
*/
function retry_wp_remote_request( $url, $args = array(), $retry_curl_codes = array(6, 28), $max_retries = 3 ) {
$retry_count = 0;
$wait_time = 2; // Initial wait time in seconds.
while ( $retry_count < $max_retries ) {
$response = wp_remote_request( $url, $args );
if ( ! is_wp_error( $response ) ) {
return $response;
}
$error_message = $response->get_error_message();
$should_retry = false;
foreach ( $retry_curl_codes as $code ) {
if ( false !== strpos( $error_message, "cURL error $code:" ) ) {
$should_retry = true;
break;
}
}
if ( ! $should_retry ) {
return new \WP_Error( 'http_request_failed', $error_message );
}
$retry_count++;
sleep( $wait_time );
$wait_time *= 2; // Exponential backoff
}
return new \WP_Error( 'http_request_failed', 'Max retries reached' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment