Codeable info

Schedule On-Going Events in WordPress

Posted on by in WordPress Tutorials

Have you ever wanted to send out emails everyday with the latest information from your site, such as all of the latest posts, or latest comments? WordPress gives us a really simple function that allows us to do exactly that.

The function looks like this:

wp_schedule_event($timestamp, $recurrence, $hook, $args);

$timestamp is the number of seconds, from the time the event is scheduled, until the event takes place for the first time. The timestamp must be in a Unix timestamp format.

$recurrence is how often the event should take place. Optional values are:

  • hourly
  • twicedaily
  • daily

$hook is the action hook to be exceuted.

$args are optional arguments that can be passed to the function called by $hook.

So, for example, let’s say we want to execute a function that emails all of our subscribers once a day. First, our email function will be something like this:

1
2
3
4
function email_subscribers()
{
     // function code here
}

Next we need to create a WordPress action hook that will be linked to our email_subscribers function:

1
add_action('email_subscribers_action', 'email_subscribers');

Then our schedule function looks like this:

1
2
3
4
5
6
7
function schedule_emails()
{
    // this checks to make sure this event isn't already scheduled
    if ( !wp_next_scheduled( 'email_subscribers_action' ) ) {
        wp_schedule_event(time(), 'daily', 'email_subscribers_action');
    }
}

By passing the PHP time() function to wp_schedule_event, we specify that the first occurrence of the event should happen now.

The final step is to hook our schedule function into WordPress so that it gets initiated.

1
add_action('wp', 'schedule_emails');

Assuming you have written the function that does the actual emailing, you now have a schedule set up that will send out an email once a day.

If you’d like further tips on how adjust the time your event gets scheduled for, and to learn about how to schedule one-time-only events, check out my Events With WP Schedule Single Event post.

For further reference, read the WordPress Codex entry.

Hope you enjoy it!

Cheers,

Pippin

Comments Closed

Codeable info