Setting up your own cron jobs in Wordpress is quite simple using the Wordpress filter cron_schedules. I’ve searched the web high and low for info related to adding your own cron job to Wordpress and this blog post has got to be by far the most informative.
There is one thing missing from the post and that’s making sure your cron is compatible with all other cron jobs that other plugins may add.
I have written a plugin that uses the cron_schedules filter to add a cron job. I wrote it as was suggested in Slaven’s blog post. Then a few months later, one of my plugin users reported that the cron job of my plugin was not running at all. It took me quite a few hours of testing but I finally figured out that another plugin’s cron was overwriting my cron.
So, here’s how to ensure that your cron job plays nicely with other cron jobs. The code I use here is based on the tutorial by Slaven which you should definitely check out.
Here is the original function which adds the new cron to Wordpress’s cron_schedules:
function more_reccurences() {
return array (
'weekly' => array('interval' => 604800, 'display' => 'Once Weekly'),
'fortnightly' => array('interval' => 1209600, 'display' => 'Once Fortnightly'),
);
} |
Now, to make sure that your schedules do not overwrite any other cron schedules:
function more_reccurences($schedules) {
$schedules['weekly'] = array('interval' => 604800, 'display' => 'Once Weekly');
$schedules['fortnightly'] = array('interval' => 1209600, 'display' => 'Once Fortnightly');
return $schedules;
} |
In this example, we pass the $schedules variable to the more_reccurences() function so we have access to it from within the function. Then, we add two new associative arrays to the $schedules variable. Finally, return the $schedules variable with your new values added but without overwriting any of the crons that might have been set by other plugins.
I’ve had many users test this method setting a cron job and I haven’t had any problems so far. Again, I would like to thank Slaven for his original tutorial!