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);
}

Related posts

Leave a Reply

2 comments

  1. 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/.