Skip to main content
Robert Michalski

Make multiple concurrent HTTP requests using WordPress

PHP code is blocking which means it runs sequentially line by line. When making HTTP requests one by one each requests must wait for the previous one to finnish, greatly slowing down the page loading time. WordPress uses Requests for PHP library to make HTTP requests under the hood, which has support for making multiple concurrent HTTP requests. Doing this can increase performance, rendering pages and responding faster to requests.

$request1 = [
	'url' => 'https://api1.com/resource',
	'type' => 'GET'
];
$request2 = [
	'url' => 'https://api2.com/resource',
	'type' => 'POST'
	'data' => [
	    'name' => 'Robert',
    ]
];
// All requests will run concurrently until all have either gotten a response or failed
$responses = Requests::request_multiple([ $request_1, $request_2 ]);
// responses need to be checked if they were successful or failed before the results are used
foreach ($responses as $response) {
	$data = [];
	if (is_a($response, 'Requests_Response')) {
	    // do stuff with successful response
	    $data[] = json_decode($response->body);
        ...
	} else {
	    // $response is a Requests_Exception
	    // Discard failed response, log or throw error
        ...
	}
}