WP Cron, scheduled events aanmaken

10-07-2020

wordpress

WP Cron is een handig alternatief voor de traditionele cronjobs en vrij gemakkelijk te realiseren. Enige kanttekening is dat je website uiteraard wel regelmatig bezocht moet worden anders heb je kans dat de cron alsnog niet draait.

Hieronder een basis voor het opzetten van scheduled events op basis van de WP Cron:

// register activation hook
register_activation_hook( __FILE__, 'example_activation' );

// function for activation hook
function example_activation() {
    // check if scheduled hook exists
    if ( !wp_next_scheduled( 'my_event' )) {
    // Schedules a hook
    // time() - the first time of an event to run ( UNIX timestamp format )
    // 'hourly' - recurrence ('hourly', 'twicedaily', 'daily' )
    // 'my_event' - the name of an action hook to execute.
    wp_schedule_event( time(), 'hourly', 'my_event' );
    }
}

add_action( 'my_event', 'do_this_hourly' );

// the code of your hourly event
function do_this_hourly() {
    // put your code here
}

// register deactivation hook
register_deactivation_hook(__FILE__, 'example_deactivation');

// function for deactivation hook
function example_deactivation() {
    // clear scheduled hook
    wp_clear_scheduled_hook( 'my_event' );
}

Wil je een afwijkend tijdspatroon? Zie dit voorbeeld om deze aan te maken:

add_filter( 'cron_schedules', 'wptest_add_cron_interval' );
function wptest_add_cron_interval( $schedules ) {
    $schedules['everyminute'] = array(
        'interval'  => 60, // time in seconds
        'display'   => 'Every Minute'
    );
    return $schedules;
}

Wat je dus weer als volgt kunt aanroepen:

wp_schedule_event( time(), 'everyminute', 'my_event' );

Voor meer info: https://wpshout.com/wp_schedule_event-examples/

Kom je er alsnog niet uit en heb je hulp nodig? Aarzel niet om contact op te nemen!
About image