Using WordPress ‘pre_clear_scheduled_hook’ PHP filter

The pre_clear_scheduled_hook filter allows you to intercept or modify the process of clearing a scheduled hook in WordPress before it is executed.

Usage

add_filter('pre_clear_scheduled_hook', 'your_custom_function', 10, 4);
function your_custom_function($pre, $hook, $args, $wp_error) {
    // your custom code here
    return $pre;
}

Parameters

  • $pre (null|int|false|WP_Error) – The value to return instead. Default is null to continue unscheduling the event.
  • $hook (string) – The action hook, the execution of which will be unscheduled.
  • $args (array) – The arguments to pass to the hook’s callback function.
  • $wp_error (bool) – Whether to return a WP_Error on failure.

Examples

Prevent unscheduling a specific hook

add_filter('pre_clear_scheduled_hook', 'prevent_unscheduling_hook', 10, 4);
function prevent_unscheduling_hook($pre, $hook, $args, $wp_error) {
    if ($hook == 'my_specific_hook') {
        return false;
    }
    return $pre;
}

This example prevents unscheduling a specific hook called my_specific_hook.

Log unscheduling events

add_filter('pre_clear_scheduled_hook', 'log_unscheduling_events', 10, 4);
function log_unscheduling_events($pre, $hook, $args, $wp_error) {
    error_log('Unscheduling hook: ' . $hook);
    return $pre;
}

This example logs the unscheduling events for hooks to the PHP error log.

Customize unscheduling of hooks based on arguments

add_filter('pre_clear_scheduled_hook', 'customize_unscheduling_based_on_args', 10, 4);
function customize_unscheduling_based_on_args($pre, $hook, $args, $wp_error) {
    if ($hook == 'my_custom_hook' && isset($args[0]) && $args[0] == 'important') {
        return false;
    }
    return $pre;
}

This example prevents unscheduling of my_custom_hook if the first argument is ‘important’.

Change behavior when unscheduling fails

add_filter('pre_clear_scheduled_hook', 'change_failure_behavior', 10, 4);
function change_failure_behavior($pre, $hook, $args, $wp_error) {
    if ($wp_error) {
        // Change behavior when unscheduling fails
        // e.g. send an email notification
    }
    return $pre;
}

This example shows how to change the behavior when unscheduling fails (e.g., by sending an email notification).

Return the number of unscheduled events

add_filter('pre_clear_scheduled_hook', 'return_unscheduled_events_count', 10, 4);
function return_unscheduled_events_count($pre, $hook, $args, $wp_error) {
    // Assuming you have a custom function to get the number of unscheduled events for the hook
    $unscheduled_events_count = get_unscheduled_events_count($hook);
    return $unscheduled_events_count;
}

This example demonstrates how to return the number of events that were successfully unscheduled.