You probably already know that WordPress can schedule events. For example, it can publish posts at preset dates and times. Using hooks and wp-cron
, we can easily schedule our own events. In this example, we will get our WordPress blog to send us an email once hourly.
Paste the following code block in the functions.php file of your theme.
if (!wp_next_scheduled('my_task_hook')) {
wp_schedule_event( time(), 'hourly', 'my_task_hook' );
}
add_action( 'my_task_hook', 'my_task_function' );
function my_task_function() {
wp_mail('you@yoursite.com', 'Automatic email', 'Hello, this is an automatically scheduled email from WordPress.');
}
// Uncomment to clear hook if not being used anymore
// wp_clear_scheduled_hook('pw_hook_schedule_weblink_token');
The first thing we did, of course, was create a function that performs the desired action. In this example, the function is called my_task_function()
and it just sends an email to the specified email address.
To schedule an event, we have to use the wp_schedule_event()
function. The last argument has to be a hook, which is why we hook our my_task_function()
function to my_task_hook
.