Created
February 24, 2020 00:45
-
-
Save MogulChris/366512bd77b286fe4a3768bcd22de18a to your computer and use it in GitHub Desktop.
Scheduling a Wordpress Cron Job (with custom schedule)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//This is how to set up a cron job via PHP in WordPress. | |
//Do not rely on simply adding it via a plugin like WP Crontrol, as WordPress occasionally loses cron jobs or fails to reschedule them. | |
//1. Add the function you want to run regularly, and an action which will trigger the function. | |
function mytheme_cron_function(){ | |
//Do some things... your custom code goes here. | |
} | |
add_action('mytheme_cron_hook','mytheme_cron_function');//name of action, name of function to run | |
//2. Add 10-min cron schedule. This is just an aribtrary interval of seconds, with a name. | |
function mytheme_add_ten_minute_schedule( $schedules ) { | |
if(!empty($schedules['ten_minutes'])) return $schedules; //don't overwrite if this schedule already exists | |
$schedules['ten_minutes'] = array( | |
'interval' => 600, //seconds | |
'display' => 'Every 10 mins' | |
); | |
return $schedules; | |
} | |
add_filter( 'cron_schedules', 'mytheme_add_ten_minute_schedule' ); | |
//3. Add cron job if not already scheduled | |
$args = array(); | |
if ( ! wp_next_scheduled( 'mytheme_cron_hook', $args ) ) { | |
wp_schedule_event( time(), 'ten_minutes', 'mytheme_cron_hook', $args ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment