WordPress cron

WordPress cron can schedule an action. The cron action will trigger when someone visits your WordPress site, if the scheduled time has passed.

<?php
function custom_plugin_activation() {
	//wp_schedule_event( time(), 'daily', 'custom_cron_job' ); // default periods: hourly, twicedaily, daily
	wp_schedule_event( time(), 'custom_cron_period', 'custom_cron_job' ); // custom cron period
}
register_activation_hook( __FILE__, 'custom_plugin_activation' );
 
 
function custom_plugin_cron_job() {
	// do something via cron with time interval
	update_option( 'custom_cron_job_option', date( 'Y-m-d H:i:s' ) );
}
add_action( 'custom_cron_job', 'custom_plugin_cron_job' );
 
 
function custom_plugin_deactivation() {
	wp_clear_scheduled_hook( 'custom_cron_job' );
}
register_deactivation_hook( __FILE__, 'custom_plugin_deactivation' ); // remove cron job after plugin deactivation
 
 
function custom_cron_period_add( $schedules ) {
	$schedules['custom_cron_period'] = array( // add a 'custom_cron_period' schedule to the existing set
		'interval' => 604800, // 60*60*24*7=7 days
		'display' => __( 'Custom period check' )
	);
	return $schedules;
}
add_filter( 'cron_schedules', 'custom_cron_period_add' ); // add custom cron period
?>

Leave a Reply

Your email address will not be published. Required fields are marked *