Running a Function Weekly in WordPress

Today’s focus is on the WordPress function wp_schedule_event().

From The Codex

“[wp_schedule_event] schedules a hook which will be executed by the WordPress actions core on a specific interval, specified by you. The action will trigger when someone visits your WordPress site, if the scheduled time has passed. See the Plugin API for a list of hooks.”

Usage

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

I know sometimes with technical blogs, it’s hard to see the application to daily life, so now I’ll share a real-life example.

Running a Function Every Week

Or, wp_schedule_event() and cron_schedules IRL
So my boss asked me to use wp_schedule_event() in conjunction with a function I’d be writing to check for “inactive” users that had not logged in to our site for at least 30 days. The function compiles a list of the inactive users every Monday morning, then sends them a login reminder email via Mandrill API.

You’ll notice, however, that “weekly” is not an option for wp_schedule_event‘s parameter $recurrance. (It only takes “hourly,” “twicedaily,” and “daily.”) So before we can schedule our event, we need to add “weekly” to the cron_schedules. That can be achieved with the following:

 add_filter( 'cron_schedules', 'rose_add_weekly' );
 
 function rose_add_weekly( $schedules ) {
 	$schedules['weekly'] = array(
 		'interval' => 604800, // 604800 seconds = 1 week
 		'display' => __( 'Once Weekly' )
 	);
 	return $schedules;
 }

As you can see, this filter simply adds a new schedule to the $schedules array.

So now we can return to our wp_schedule_event(). In my case, I set the $timestamp parameter to the UNIX timestamp of the next Monday.

* Please note, the scheduled event will not be set if the site isn’t visited. So if you set $timestamp to be “time() + 3600,” the $hook will run one hour after the next visit. Once the event is scheduled, the $recurrance will continue to run regardless of visits.

The next parameter is $recurrance, which is where we put our newly created “weekly” cron schedule.

Then, $hook is just the function for whatever you want to run on a weekly basis (my function is described above).

The below code will run at the first visit, time(), then weekly afterwards.

wp_schedule_event( time(), 'weekly', 'rose_alarm_clock', $args );

So that’s how you schedule weekly events in WordPress! Hope it’s helpful. Let me know if it’s not or if there’s something else you want me to cover.