Skip to content

Instantly share code, notes, and snippets.

@adamdehaven
Last active November 1, 2018 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adamdehaven/b10ca8d8cf961fde44d520ad7132a8a0 to your computer and use it in GitHub Desktop.
Save adamdehaven/b10ca8d8cf961fde44d520ad7132a8a0 to your computer and use it in GitHub Desktop.
Schedule events in WordPress

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.

The solution

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');

Code explanation

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.

@quangpro1610
Copy link

Hi @adamdehaven,
About the wp_schedule_event() function, it will launch auto and we don't need to hook to any the actions? Is that right?
Thank you so much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment