Using WordPress ‘pre_get_scheduled_event’ PHP filter

pre_get_scheduled_event is a WordPress PHP filter that allows you to modify or intercept the retrieval of a scheduled event before it happens.

Usage

add_filter('pre_get_scheduled_event', 'your_custom_function', 10, 4);

function your_custom_function($pre, $hook, $args, $timestamp) {
    // your custom code here
    return $pre;
}

Parameters

  • $pre (null|false|object) – Value to return instead. Default null to continue retrieving the event.
  • $hook (string) – Action hook of the event.
  • $args (array) – Array containing each separate argument to pass to the hook’s callback function. These arguments are used to uniquely identify the event, even though they are not passed to a callback.
  • $timestamp (int|null) – Unix timestamp (UTC) of the event. Null to retrieve the next scheduled event.

More information

See WordPress Developer Resources: https://developer.wordpress.org/reference/hooks/pre_get_scheduled_event/

Examples

Bypass event retrieval

Bypass the retrieval of a specific event.

add_filter('pre_get_scheduled_event', 'bypass_specific_event', 10, 4);

function bypass_specific_event($pre, $hook, $args, $timestamp) {
    if ($hook === 'my_custom_hook' && $args[0] === 'specific_arg') {
        return false;
    }
    return $pre;
}

Modify event timestamp

Change the timestamp of a scheduled event.

add_filter('pre_get_scheduled_event', 'modify_event_timestamp', 10, 4);

function modify_event_timestamp($pre, $hook, $args, $timestamp) {
    if ($hook === 'my_custom_hook') {
        $timestamp += 3600; // Add one hour
    }
    return $pre;
}

Log events

Log events that match specific criteria.

add_filter('pre_get_scheduled_event', 'log_matching_events', 10, 4);

function log_matching_events($pre, $hook, $args, $timestamp) {
    if ($hook === 'my_custom_hook' && count($args) === 2) {
        error_log("Matched event: {$hook}, args: " . implode(', ', $args) . ", timestamp: {$timestamp}");
    }
    return $pre;
}

Replace event with custom event

Replace the scheduled event with a custom event.

add_filter('pre_get_scheduled_event', 'replace_event_with_custom', 10, 4);

function replace_event_with_custom($pre, $hook, $args, $timestamp) {
    if ($hook === 'my_custom_hook') {
        $custom_event = new stdClass;
        $custom_event->hook = 'my_replacement_hook';
        $custom_event->args = $args;
        $custom_event->timestamp = $timestamp;
        return $custom_event;
    }
    return $pre;
}

Cancel specific event

Cancel the scheduled event based on specific criteria.

add_filter('pre_get_scheduled_event', 'cancel_specific_event', 10, 4);
function cancel_specific_event($pre, $hook, $args, $timestamp) {
    if ($hook === 'my_custom_hook' && $args[0] === 'cancel_this') {
        wp_unschedule_event($timestamp, $hook, $args);
        return false; 
    } 
return $pre; 
}