Use Hooks And Cron To Schedule Events

Use Hooks And Cron To Schedule Events

Sm9 in 10 Useful WordPress Hook Hacks

The problem.
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.

1 if (!wp_next_scheduled('my_task_hook')) {
2     wp_schedule_event( time(), 'hourly''my_task_hook' );
3 }
5 add_action( 'my_task_hook''my_task_function' );
7 function my_task_function() {
8     wp_mail('you@yoursite.com''Automatic email''Hello, this is an automatically scheduled email from WordPress.');
9 }

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.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s