WP Cron job every 1st and 15th of the month

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;

}

2 Answers
2

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:

cron_callback_wpse_113675() {
  $date = date('d');
  if ('01' == $date || '15' == $date) {
    // run your function
  }
}

Or, use wp_schedule_single_event with a more complicated callback. Something like this:

function cron_callback_v2_wpse_113675() {
  $date = date('d');
  if (!wp_next_scheduled(cron_callback_v2_wpse_113675)) {
    $date = ($date < 15) ? '15' : '01';
  }
  if ('01' == $date || '15' == $date) {
    // run your function
    switch ($date) {
      case '01' :
        wp_schedule_single_event( strtotime('+14 days',strtotime('first day of')), 'cron_callback_v2_wpse_113675' );
      break;
      case '15' :
        wp_schedule_single_event( strtotime('first day of'), 'cron_callback_v2_wpse_113675' );
      break;
    }
  }
}

Barely Completely untested. Possibly buggy. Caveat emptor. No refunds.

Leave a Comment