7

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?

5
  • Please check this github.com/techcrunch/wp-async-task Commented Feb 12, 2018 at 7:40
  • 1
    Is this project(wp-async-task ) still alive on WP 4.9(no commit for last 3 years)? Also, this seems to run a background process related to a hook and bit doubtful if I can call multiple HTTP requests using that like we do in AJAX using promise Commented Feb 12, 2018 at 8:28
  • You can send multiple async HTTP requests using Ajax and can handle those request using ajax request handler codex.wordpress.org/AJAX_in_Plugins . wp-async-task is still compatible with WordPress latest version and it handles async taks in server. Commented Feb 12, 2018 at 9:12
  • 1
    But I want to do it from backend using PHP and not from Javascript so AJAX might not help Commented Feb 12, 2018 at 9:15
  • Then wp-async-task is 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/… Commented Feb 12, 2018 at 10:45

1 Answer 1

6

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;
}
1
  • 1
    Please note that the foreach at the end is not complete. It's just there to demonstrate how to use it. You'll potentially also have to handle the Requests_Exception. Commented Apr 9, 2018 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.