Automate tasks with wp_cron - read how to set one up, add new frequencies and some debugging tips.
cron is a service on Unix operating systems that runs tasks at specified times. Tasks can be run as frequently as every minute. WordPress provides its own version of cron. WordPress core uses this feature to check for new versions of WordPress, themes and plugins. It also uses it to empty the post and pages trash.
I will write a simple example to report the latest published posts. This is a silly example but it will not require much code and so the cron code will not be lost amongst the non-cron code.
I found the very detailed post Schedule Events Using WordPress Cron on Smashing Magazine to be very helpful. It details how wp_cron works and its limitations.
Adding Schedule Option
WordPress provides three frequency options – hourly, twice daily and daily. For additional frequency options you will need to add them yourself.
In a client site I added weekly and biweekly options to send a status email at the end of each week.
Set up Task
In a client site I created a CPT of project statuses. Each week an email is sent listing all the statuses. wp_cron was an ideal solution. The CPT and cron code were both in a plugin (because they should persist if the theme is changed).
The code starts by registering code to run when the plugin is activated – this code schedules the task to run at the specified time (the next 2:12am).
It also registers code to run when the plugin is deactivated – to the task from wp_cron.
Write the Task
The scheduled task can be anything you want.
Here the code retrieves a list of posts published this week.
Debugging Tasks
Debugging scheduled task code can be difficult as you can’t echo out variables and other debug information. You should enable debug mode and add some error_log() calls.
As you are dealing with scheduled tasks and will want to run the task outside the scheduled times you can use a plugin to help. WP Control and Advanced Cron Manager allow you view scheduled tasks (useful to check that your wp_schedule_event() call worked) and to run a task immediately.
I recommend creating a shortcode to run the task. Put the shortcode in a page and refresh the page as often as necessary. You can include your debug code in the output. When it is working you can disable the shortcode.
Run wp_cron without visitors
To run wp_cron requires that your site has visitors. If you have a busy site then this will work, otherwise tasks may not run until well after their scheduled time. You can overcome this by disabling wp_cron and invoke it directly.
To prevent wp_cron running you can disable it in wp-config.php.
You then need to use real cron on your host to run wp-cron.php so that it will run the scheduled tasks.
My host has a plesk control panel and I use the following command:
It is set to run every 30 minutes. It will run even if no one visits the site.
Leave a Reply