Skip to content

Instantly share code, notes, and snippets.

@trey8611
Last active March 29, 2025 21:10
Show Gist options
  • Save trey8611/90d25ac325a026b0992f0a622dc0dc85 to your computer and use it in GitHub Desktop.
Save trey8611/90d25ac325a026b0992f0a622dc0dc85 to your computer and use it in GitHub Desktop.
[Change cURL Header and other options] Change timeout settings, headers, pass tokens, etc. #curl #download-from-url

You can use the http_api_curl hook to change timeout settings, headers, etc, when downloading a feed via URL with WP All Import.

There are example snippets below that you can modify for your use case. This code needs to be saved in your child theme's functions.php file, or in a plugin like Code Snippets.

Examples

Basic Authentication (base64_encode)

add_action( 'http_api_curl', 'example_set_curl_auth', 10, 3 );
function example_set_curl_auth( $handle, $r, $url ) {
	if ( strpos( $url, 'api.example.com/feed' ) !== false ) {
		$user = 'yourusername';
		$pass = 'yourpassword';
		curl_setopt( $handle, CURLOPT_USERPWD, $user . ':' . $pass );
		curl_setopt( $handle, CURLOPT_TIMEOUT, 180 );
		curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, 180 );
		
	}
}

Change timeout settings and follow redirect for Google Sheets

add_action( 'http_api_curl', 'example_set_curl_for_gdocs', 10, 3 );
function example_set_curl_for_gdocs( $handle, $r, $url ) {
	if ( strpos( $url, 'docs.google.com' ) !== false ) {
		curl_setopt( $handle, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36" );
		curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, true );
		curl_setopt( $handle, CURLOPT_TIMEOUT, 180 );
		curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, 180 );
	}
}

Fetch token to use in API request

function get_feed_token() {
	
	$ch = curl_init();

	curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/api/auth/token/obtain/');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"username\":\" yourusername \",\"password\":\"yourpassword\"}");

	$headers = array();
	$headers[] = 'Content-Type: application/json';
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );

	$result = curl_exec( $ch );
	if ( curl_errno( $ch ) ) {
		return false;
	}
	curl_close( $ch );
	
	$response = json_decode( $result, true );
	
	return empty( $response['access'] ) ? '' : $response['access'];
}

function my_curl_header( $handle, $r, $url ) {
    if ( strpos( $url, 'myfeed.url.com' ) !== false ) {
        $token = get_feed_token();
		$headers = array();
		$headers[] = 'Authorization: Bearer ' . $token;
		$headers[] = 'Content-Type: application/json';
		curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );    				
	}
}

add_action( 'http_api_curl', 'my_curl_header', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment