Schedule event every second thursday of the month

WordPress lets you add custom cron schedules, which is normally what you’d want to do in this situation, in conjunction with wp_schedule_event(). But, they work based on intervals rather than specific dates/times. For instance,

add_filter( 'cron_schedules', 'addCustomCronIntervals' );
function addCustomCronIntervals( $schedules )
{
    $schedules[ self::PREFIX . 'debug' ] = array(
        'interval'  => 60 * 2,
        'display'   => 'Every 2 minutes'
    );

    return $schedules;
}

So, instead, you could do it with your current approach, but you’ll also need to setup a transient to make sure the e-mails aren’t sent every time the page loads.

$firstThursday = date_i18n( 'Ymd', strtotime( 'first thursday this month', current_time( 'timestamp' ) ) );
$today = date_i18n( 'Ymd', current_time( 'timestamp' ) );
if( strcmp( $firstThursday, $today ) === 0 && ! get_transient( 'alreadySentEmails' ) )
{
    send_emails();
    set_transient( 'alreadySentEmails', 60 * 60 * 24 );
}

Note that you should be using WordPress’ date_i18n() and current_time() functions instead of PHP’s date() and time() – which strtotime() implicitly calls -, so that time zones are handled correctly.

Also note that some relative formats are new to PHP 5.3, so make sure your server is current.

Leave a Comment