How To Create Custom WordPress Cron Intervals

This is mostly a reminder for myself so I can stop tracking it down every time I forget, but here’s how to have WordPress code execute on a different schedule than the default intervals of hourly, twicedaily, and daily. This specific example is for weekly execution.

<?php

// Add a new interval of a week
// See http://codex.wordpress.org/Plugin_API/Filter_Reference/cron_schedules
add_filter( 'cron_schedules', 'myprefix_add_weekly_cron_schedule' );
function myprefix_add_weekly_cron_schedule( $schedules ) {
	$schedules['weekly'] = array(
		'interval' => 604800, // 1 week in seconds
		'display'  => __( 'Once Weekly' ),
	);

	return $schedules;
}

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'myprefix_my_cron_action' ) ) {
	wp_schedule_event( time(), 'weekly', 'myprefix_my_cron_action' );
}

// Hook into that action that'll fire weekly
add_action( 'myprefix_my_cron_action', 'myprefix_function_to_run' );
function myprefix_function_to_run() {
	// Add some code here
}

?>

On a side note, I believe this must go in a plugin and not your theme’s functions.php which I hear loads too late.

7 thoughts on “How To Create Custom WordPress Cron Intervals

  1. Pingback: Custom WordPress Cron Intervals | Matt's Technology Blog

  2. Pingback: Creating custom WordPress cron intervals | WPCandy

  3. Pingback: WordPress Community Roundup for the Week Ending December 17 - Charleston WordPress User Group

  4. Pingback: Custom WordPress Cron Intervals | Matt's Technology Blog

  5. Hello , i am new in wordpress , when i use your code in my php page , it show me Fatal error: Uncaught Error: Call to undefined function add_filter() in C:\xampp\htdocs\wordpress\wp-content\plugins\dkdrbooking\include\dkbooking_schedule_reset_time.php:6 Stack trace: #0 {main} thrown in C:\xampp\htdocs\wordpress\wp-content\plugins\dkdrbooking\include\dkbooking_schedule_reset_time.php on line 6
    what i need to do ?

  6. Pingback: Menjadwalkan Fungsi Dengan cronjob & membuat file json - Lasida Work

Comments are closed.