In my plugin, I want to call 10 or more HTTP requests asynchronously in WordPress so that I need not wait for the response of anyone. Is there any way in Wordpress that supports this and also compatible with different WordPress versions?
1 Answer
The (built-in) Requests class lets you call multiple requests simultaneously: Requests::request_multiple.
<?php
$requests = Requests::request_multiple([
[
'url' => 'https://www.mocky.io/v2/5acb821f2f00005300411631',
'type' => 'GET',
'headers' => [
'Accept' => 'application/json'
],
],
[
'url' => 'https://www.mocky.io/v2/5acb821f2f00005300411631',
'type' => 'POST',
'headers' => [
'Accept' => 'application/json'
],
'data' => json_encode([
'text' => 'My POST Data'
])
],
[
'url' => 'https://www.mocky.io/v2/5acb82ee2f00005100411635',
'type' => 'POST',
'headers' => [
'Accept' => 'application/json'
],
'data' => json_encode([
'text' => 'More POST Data'
])
],
]);
foreach ($request as $request) {
if ($request->status_code !== 200) {
// handle error
}
// handle success
echo $request->body;
}
-
1Please note that the
foreachat the end is not complete. It's just there to demonstrate how to use it. You'll potentially also have to handle theRequests_Exception.alpipego– alpipego2018-04-09 15:19:15 +00:00Commented Apr 9, 2018 at 15:19
wp-async-taskis still compatible with WordPress latest version and it handles async taks in server.wp-async-taskis what you need. Please check the following links for more details torquemag.io/2016/01/use-asynchronous-php-wordpress techcrunch.com/2014/07/31/… stackoverflow.com/questions/35924616/…