I am using this code in my functions.php which works fine. However, I was wondering if this is the best practice to do so to schedule an event, or if there is a better solution.

if (!wp_next_scheduled('my_task_hook')) {
    wp_schedule_event( time(), 'daily', 'my_task_hook' );

add_action( 'my_task_hook', 'my_task_function' ); 

function my_task_function() {
    wp_mail('myemail@example.com', 'Test Email', 'Hello, this is a test automatically scheduled email from WordPress.');
  • Yes, that's actually the standard way to use this function. However, you should wrap your conditional inside a function, and hook it to an action such as init. – Jack Johansson Oct 22 '18 at 18:41
  • Hi Jack, the way I enlisted my code, works just fine and I can see the event scheduled in WP Cron. Why do I need to hook it up to 'init'? – Joanna Mikalai Oct 22 '18 at 19:30
  • It's considered best practices to hook your functions to action hook, so they are ran exactly at the point you want them to, making sure it always runs as expected. I pointed out this since you asked for the best practice. – Jack Johansson Oct 22 '18 at 19:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.