Asynchronous functions in Wordpress 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 activated. This would be useful if MY_FUNCTION() was going to do something that would take a long time. 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.