Asynchronous functions in Wordpress 5/28/13

By Chris Johnson

Last Tuesday I went to the local Wordpress Meetup where Jack Reichert gave an excellent talk on using Wordpress actions and filters. In one especially clever example, he combined an action with wp_schedule_single_event() to run a bit of code asynchronously:

<?php
function MY_CRON(){
  wp_schedule_single_event(time(), 'MY_ACTION');
}
add_action('save_post', 'MY_CRON');
 
function MY_FUNCTION(){
  // YOUR CODE HERE
}
add_action('MY_ACTION', 'MY_FUNCTION');

After a post is saved, MY_FUNCTION() is scheduled to run the next time Wordpress’s pseudo-cron system is activated1. This would be useful if MY_FUNCTION() was going to do something that would take a long time2. Instead of forcing the user to wait for MY_FUNCTION() to finish, they’ll see that the post saved immediately and can go about their business.

This example uses save_post, but you could tie it to any of the other Wordpress actions that are available.

  1. Wordpress’s pseudo-cron is run when a page is loaded on your site. If you get low traffic, your cron jobs may not be run anytime close to when you intended. You can use a plugin like Cron View to see what’s scheduled. 

  2. Anything involving data transfers with another server would be a good candidate.