The ‘pre_unschedule_hook’ filter allows you to intercept and modify the process of unscheduling events attached to a specific action hook in WordPress.
Usage
add_filter( 'pre_unschedule_hook', 'your_custom_function', 10, 3 ); function prevent_unscheduling_hook( $pre, $hook, $wp_error ) { return $pre; }
Parameters
- $pre (null|int|false|WP_Error)
- The value to return instead of continuing the unscheduling process.
- Default is null.
- $hook (string)
- The action hook whose events will be unscheduled.
- $wp_error (bool)
- Whether to return a WP_Error on failure.
Examples
Prevent unscheduling events for a specific hook
add_filter( 'pre_unschedule_hook', 'prevent_unscheduling_hook', 10, 3 ); function prevent_unscheduling_hook( $pre, $hook, $wp_error ) { if ( 'my_custom_hook' === $hook ) { return false; } return $pre; }
This code prevents unscheduling events attached to the ‘my_custom_hook’ action hook. If the hook being unscheduled is ‘my_custom_hook’, it returns false, leaving the events scheduled.
Display a custom error message for a specific hook
add_filter( 'pre_unschedule_hook', 'custom_error_unscheduling_hook', 10, 3 ); function custom_error_unscheduling_hook( $pre, $hook, $wp_error ) { if ( 'my_custom_hook' === $hook && $wp_error ) { return new WP_Error( 'custom_error', 'You cannot unschedule this hook.' ); } return $pre; }
This code displays a custom error message when trying to unschedule events attached to the ‘my_custom_hook’ action hook and the $wp_error
parameter is set to true.
Count events before unscheduling
add_filter( 'pre_unschedule_hook', 'count_events_before_unscheduling', 10, 3 ); function count_events_before_unscheduling( $pre, $hook, $wp_error ) { $events = wp_get_scheduled_hook( $hook ); error_log( 'There are ' . count( $events ) . ' events attached to ' . $hook ); return $pre; }
This code logs the number of events attached to the action hook before proceeding with the unscheduling process.
Unschedule events conditionally
add_filter( 'pre_unschedule_hook', 'conditionally_unschedule_hook', 10, 3 ); function conditionally_unschedule_hook( $pre, $hook, $wp_error ) { if ( 'my_custom_hook' === $hook && some_custom_condition() ) { return false; } return $pre; }
This code prevents unscheduling events attached to the ‘my_custom_hook’ action hook if a custom condition is met, determined by the some_custom_condition()
function.
Change the hook to unschedule
add_filter( 'pre_unschedule_hook', 'change_hook_to_unschedule', 10, 3 ); function change_hook_to_unschedule( $pre, $hook, $wp_error ) { if ( 'original_hook' === $hook ) { return wp_unschedule_hook( 'new_hook', $wp_error ); } return $pre; }
This code intercepts the unscheduling process for the ‘original_hook’ action hook and unschedules events attached to the ‘new_hook’ action hook instead.