hook => events. Core removes a timestamp once its last event is * unscheduled. A plugin that edits the array itself can leave the emptied * entries behind. The case this was written for is Kadence Security: when its * scheduler removes one of its own events * (ITSEC_Scheduler_Cron::unschedule_by_hash()), it writes the array back with * the emptied "itsec_cron" entry still in place, so the option keeps growing. * The option is loaded and unserialized on every request and rewritten on * every schedule change. * * Two parts: * - A filter on the cron option drops hooks that hold no events and timestamps * that hold no hooks whenever the option is about to be saved, which is what * core itself does in wp_unschedule_event(). * - A check once per request, after WordPress has loaded, clears entries that * are already there (for example on the first request after the setting is * enabled). It only writes when it finds an empty entry. * * Scheduled events are never changed. Not specific to Kadence Security in what * it removes: an empty slot has no meaning to WordPress whoever left it. A no-op * on a site without the problem. It does not reduce how often the option is * written, only how large it is. * * Loaded only when the "cron_empty_slot_cleanup" option is enabled. * * @package Agency_Toolkit */ // Standard WP check if direct. defined( 'ABSPATH' ) || exit; /** * Removes hooks without events and timestamps without hooks from a cron array. * * @param mixed $crons The cron array about to be saved (timestamp => hook => events, * plus the "version" key). * @return mixed The same array without empty slots; anything unexpected is returned as is. */ function inspry_toolkit_prune_empty_cron_slots( $crons ) { if ( ! is_array( $crons ) ) { return $crons; } foreach ( $crons as $timestamp => $hooks ) { // The "version" key, or anything else that is not a timestamp's list of hooks. if ( ! is_array( $hooks ) ) { continue; } foreach ( $hooks as $hook => $events ) { if ( is_array( $events ) && ! $events ) { unset( $crons[ $timestamp ][ $hook ] ); } } if ( ! $crons[ $timestamp ] ) { unset( $crons[ $timestamp ] ); } } return $crons; } add_filter( 'pre_update_option_cron', 'inspry_toolkit_prune_empty_cron_slots' ); /** * Clears empty slots that are already stored, without waiting for the next * schedule change. Writes only when there is something to remove; the filter * above keeps new ones out after that. */ function inspry_toolkit_prune_stored_cron_slots() { $crons = _get_cron_array(); if ( ! $crons ) { return; } $pruned = inspry_toolkit_prune_empty_cron_slots( $crons ); if ( $pruned !== $crons ) { _set_cron_array( $pruned ); } } add_action( 'wp_loaded', 'inspry_toolkit_prune_stored_cron_slots' );