Trying to set up custom schedules for WP Cron, knowing that they use an interval is it even possible to set up a cron job for every first of the month? As well as every fifteenth. This is what I have so far:
private function cron_schedules( $schedules ) {
$midnight = strtotime( "midnight", current_time( 'timestamp' ) );
$first = strtotime( 'first day of this month', $midnight );
$fifteenth = $first + (7 * 24 * 60 * 60) * 2;
$schedules['1st'] = array(
'interval' => $first,
'display' => __('1st of every month'),
);
$schedules['15th'] = array(
'interval' => $fifteenth,
'display' => __('15th of every month'),
);
$schedules['weekly'] = array(
'interval' => ( 7 * 24 * 60 * 60 ),
'display' => __('Weekly'),
);
$schedules['biweekly'] = array(
'interval' => ( 7 * 24 * 60 * 60 ) * 2,
'display' => __('Biweekly'),
);
return $schedules;
}
wp_cron
operates on intervals and there is no interval that will hit exactly the first day and the 15th of every month.You could run your
wp-cron
job every day and check the date, similar to this but with a simple callback like:Or, use
wp_schedule_single_event
with a more complicated callback. Something like this:BarelyCompletely untested. Possibly buggy. Caveat emptor. No refunds.I encountered a similar issue but needed to fire an event on the last day of the month. I figured out an alternate solution that would work for this and my issue. Instead of modifying the schedules, I used the daily schedule to simply fire my monthly actions if necessary.
First I added code like this to my plugin activation to setup the daily check
Then I added a job to run daily to see if it needed to fire the monthly cron
To adjust this to fire on the 1st & 15th, you could just adjust the code above to something like this:
Then you can just use the “monthly_cron” action to perform your actions like this: