
You probably know that WordPress can schedule events. In this recipe, I’ll show you how you create an event that will be executed once hourly, or daily, etc.

You probably know that WordPress can schedule events. In this recipe, I’ll show you how you create an event that will be executed once hourly, or daily, etc.
Just paste this piece of code in your functions.php file:
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.');
}
On line 1, we created an event, after verifying that an event of the same name wasn't already registered. All we have to do then is to create a function to do what you want (In this example, the function is called my_task_function() and it simply send a dummy email) and hook this function to any WordPress event.
One Response
Hello and thank you so much for this valuable CRON script. Could you please tell me how one would change the time value in the event
“wp_schedule_event( time(), ‘hourly’, ‘my_task_hook’ );” to run a job every two weeks on a Tuesday at 6:00 PM ?
Again, thank you for sharing such a useful script.
Trackbacks: