WP-Mix

A fresh mix of code snippets and tutorials

WordPress Cron Tips

Here are some quick tips for working with WordPress Cron. The trick to using the scheduling functions is to get the next scheduled cron using wp_next_scheduled().

Getting the next scheduled cron

To get the timestamp of the next scheduled cron, include this in your function:

$timestamp = wp_next_scheduled('wpmix_cron');

Once this variable is set, scheduling functions can work their magic..

Unschedule cron event

To unschedule a cron event in WordPress:

// Unschedule cron event
function wpmix_cron_unschedule() {
	$timestamp = wp_next_scheduled('wpmix_cron');
	wp_unschedule_event($timestamp,'wpmix_cron');
}

Reschedule cron event

Likewise, to reschedule a cron event in WordPress:

// Reschedule cron event
function wpmix_cron_reschedule() {
	$timestamp = wp_next_scheduled('wpmix_cron');
	wp_unschedule_event($timestamp,'wpmix_cron');
	wp_reschedule_event(time(), 'hourly', 'wpmix_cron');
}

Schedule cron event

And here’s how to schedule a cron event (note: $timestamp not required):

// Schedule cron event
function wpmix_cron_schedule() {
	wp_schedule_event(time(), 'hourly', 'wpmix_cron');
}

Clear scheduled hook

To clear a scheduled hook:

wp_clear_scheduled_hook('wpmix_cron');

Putting it all together

Here’s an example that brings everything together. For my plugin, Simple Ajax Chat, here’s how to auto-clear all chat messages every hour. With the plugin installed, add the following code to your theme’s functions.php file:

// cron for clearing chats
add_action('wp', 'sac_cron_activation');
function sac_cron_activation() {
	if (!wp_next_scheduled('sac_cron_truncate')) {
		wp_schedule_event(time(), 'hourly', 'sac_cron_truncate'); // hourly, daily, twicedaily
	}
	// wp_clear_scheduled_hook('sac_cron_truncate');
}
// truncate chats from admin
add_action('sac_cron_truncate', 'sac_cron_truncate_chats');
function sac_cron_truncate_chats() {
	global $wpdb, $table_prefix;
	$sac_options = get_option('sac_options');
	$default_message = $sac_options['sac_default_message'];
	$default_handle  = $sac_options['sac_default_handle'];
	$wpdb->query("TRUNCATE TABLE " . $table_prefix . "ajax_chat");
	$wpdb->query("INSERT INTO " . $table_prefix . "ajax_chat (time, name, text) VALUES ('" . time() . "','" . $default_handle . "','" . $default_message . "')");
}

No editing is required, unless you want to change the clearing frequency by changing hourly to either “hourly”, “daily”, or “twicedaily”. You can see the script in action (if you wait awhile) in the Chat Demo.

Update: Here is another example of using WordPress Cron.

Note: WP Crontrol is an excellent plugin for working with WP Cron. Highly recommended :)

Related Stuff

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress