WordPress has its own cron to automatically and scheduled run certain themes. Therefore WordPress provides several functions to use the cron.
In our first example we send every hour a mail with the help of the WordPress function wp_mail()
. FYI, this is just a possibility, please don’t do it on your system!
As default, WordPress can handle 3 time keys, which you can call with the function wp_schedule_event
.
if ( ! wp_next_scheduled(‘my_task_hook’) ) {
wp_schedule_event( time(), ‘hourly’, ‘my_task_hook’ ); // hourly, daily and twicedaily
}
add_action( ‘my_task_hook’, ‘my_task_function’ );
function my_task_function() {
wp_mail(
‘example@yoursite.com’,
‘Automatic mail’,
‘Hello, this is an automatically scheduled email from WordPress.’
);
}
If you use the cron in a Plugin or theme, then don’t forget to deactivate the cron if you don’t need it anymore.
// clean the scheduler
function my_task_deactivate() {
wp_clear_scheduled_hook( ‘my_task_hook’ );
}
But not always are 3 time values enough. Luckily you can expand the control via a filter.
add_filter( ‘cron_schedules’, ‘filter_cron_schedules’ );
// add custom time to cron
function filter_cron_schedules( $param ) {
return array( ‘once_half_hour’ => array(
‘interval’ => 1800, // seconds
‘display’ => __( ‘Once Half an Hour’ )
) );
}