First, let’s start by talking about what default intervals are available within WordPress:
For most people that may be enough – but you can define your own as well; such as weekly, bi-weekly, or monthly. In fact you can create as many interval options as you want, but I’d caution you to keep only the ones you’re actually going to use.
To create additional intervals we need to use the cron_schedules filter as shown here:
add_filter( 'cron_schedules', 'my_custom_intervals' ); function my_custom_intervals( $intervals ) { // Adds new intervals to the existing intervals. $intervals['weekly'] = array( 'interval' => 604800, 'display' => __( 'Once Weekly' ) ); return $intervals; }
We need only add a new array item to the $intervals array, then set an interval (in unix time) and a display title.
You can add as many as you like by continuing to add to the $intervals array.
To schedule an event we use wp_schedule_event, as shown here:
wp_schedule_event( time(), $interval, $hook, $args);
The function wp_schedule_event takes 3 parameters;
Your code should look something like this, just to be safe:
if (!wp_next_scheduled('my_scheduled_action')) { wp_schedule_event( time(), 'daily', 'my_scheduled_action'); }
We can now create an action using the $hook parameter, like so:
if (!wp_next_scheduled('my_scheduled_action')) { wp_schedule_event( time(), 'daily', 'my_scheduled_action'); } add_action('my_scheduled_action', 'my_scheduled_action_callback'); function my_scheduled_action_callback() { // do scheduled stuff.. }
You can send arguments with wp_schedule_event, simply by using the fourth parameter, $args. Send your arguments as an associative array, and they will be sent to your callback function.
This would look like:
if (!wp_next_scheduled('my_scheduled_action')) { $args = array( 'arg1' => 'foo', 'arg2' => 'bar' ); wp_schedule_event( time(), 'daily', 'my_scheduled_action', $args); } add_action('my_scheduled_action', 'my_scheduled_action_callback'); function my_scheduled_action_callback($arg1, $arg2) { // do scheduled stuff.. }
It may be important to clear scheduled tasks if they’re no longer needed. To clear a task, we use wp_clear_scheduled_hook and pass it the name of the hook we wish to remove.
wp_clear_scheduled_hook('my_scheduled_action');
// Create some handy intervals add_filter( 'cron_schedules', 'my_custom_intervals' ); function my_custom_intervals( $intervals ) { // Adds new intervals to the existing intervals. $intervals['weekly'] = array( 'interval' => 604800, 'display' => __( 'Once Weekly' ) ); return $intervals; } // schedule an event if it's not already scheduled if (!wp_next_scheduled('my_scheduled_action')) { wp_schedule_event( time(), 'daily', 'my_scheduled_action'); } // create an action and callback add_action('my_scheduled_action', 'my_scheduled_action_callback'); function my_scheduled_action_callback() { // do scheduled stuff.. }
View your current schedule – FFF Cron Manager Plugin