Skip to content

Instantly share code, notes, and snippets.

@quangpro1610
Forked from adamdehaven/wp-schedule.md
Created November 1, 2018 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quangpro1610/2edccb0f90b69e47975f2999765f05a0 to your computer and use it in GitHub Desktop.
Save quangpro1610/2edccb0f90b69e47975f2999765f05a0 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.

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