Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous php code in WP Plugin

Need to make this block of code asynchronous with the rest of the code. Its going to collect the wp posts and send a post request to my url. The plugin should run asynchronously and doesn't hamper the functioning of the wordpress site.

for ($x=0; $x<=n; $x++) {
$data = posts[$x];
$ch = curl_init('http://myurl.com/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'ACCEPT: application/json',
'Content-Length: ' . strlen($data))
);

$result = curl_exec($ch);
curl_close($ch);
}
like image 379
Ahwan Kumar Avatar asked Nov 09 '14 09:11

Ahwan Kumar


2 Answers

The proper way to process asynchronous requests in WordPress is to use WP-Cron to schedule an event. You can either schedule it to run once, or on an interval. See some guides on setting it up here. The two main functions to check out are wp_schedule_event() and wp_schedule_single_event().

One thing to keep in mind however is that because your code is only running when there is a request, if there is low traffic then it's possible that your scheduled event won't run when expected. I wrote an article on my site regarding how you can use crontab in conjunction with WP-Cron to more accurately schedule events: http://justinsilver.com/technology/wordpress/disable-wp-cron-wordpress/.

like image 183
doublesharp Avatar answered Sep 28 '22 05:09

doublesharp


Use Guzzle Package, code sample:

$request = $client->createRequest('GET', ['future' => true]);
$client->send($request)->then(function ($response) {
    echo 'Got a response! ' . $response;
});

Look how can you install it. Also check the RingPHP and Future Responses for some additional information. Actually RingPHP is utilized as the handler layer in Guzzle and at the bottom, the React/Promise is giving the Promises/A support for PHP.

like image 37
The Alpha Avatar answered Sep 28 '22 06:09

The Alpha