WordPress.org

Make WordPress Core

Changeset 40965


Ignore:
Timestamp:
06/30/2017 12:21:49 AM (2 years ago)
Author:
SergeyBiryukov
Message:

Cron API: Introduce wp_unschedule_hook() to clear all events attached to a hook.

This complements wp_clear_scheduled_hook(), which only clears events attached with specific arguments.

Props arena, mordauk, jrf.
Fixes #18997.

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/cron.php

    r38357 r40965  
    192192
    193193/**
    194  * Unschedule all events attached to the specified hook.
     194 * Unschedule all events attached to the hook with the specified arguments.
    195195 *
    196196 * @since 2.1.0
     
    220220        }
    221221    }
     222}
     223
     224/**
     225 * Unschedule all events attached to the hook.
     226 *
     227 * Can be useful for plugins when deactivating to clean up the cron queue.
     228 *
     229 * @since 4.9.0
     230 *
     231 * @param string $hook Action hook, the execution of which will be unscheduled.
     232 */
     233function wp_unschedule_hook( $hook ) {
     234    $crons = _get_cron_array();
     235
     236    foreach( $crons as $timestamp => $args ) {
     237        unset( $crons[ $timestamp ][ $hook ] );
     238
     239        if ( empty( $crons[ $timestamp ] ) ) {
     240            unset( $crons[ $timestamp ] );
     241        }
     242    }
     243
     244    _set_cron_array( $crons );
    222245}
    223246
  • trunk/tests/phpunit/tests/cron.php

    r39554 r40965  
    187187        wp_clear_scheduled_hook($multi_hook, $multi_args);
    188188        $this->assertFalse( wp_next_scheduled($multi_hook, $multi_args) );
    189 
     189    }
     190
     191    /**
     192     * @ticket 18997
     193     */
     194    function test_unschedule_hook() {
     195        $hook = __FUNCTION__;
     196        $args = array( rand_str() );
     197
     198        // schedule several events with and without arguments.
     199        wp_schedule_single_event( strtotime( '+1 hour' ), $hook );
     200        wp_schedule_single_event( strtotime( '+2 hour' ), $hook );
     201        wp_schedule_single_event( strtotime( '+3 hour' ), $hook, $args );
     202        wp_schedule_single_event( strtotime( '+4 hour' ), $hook, $args );
     203
     204        // make sure they're returned by wp_next_scheduled().
     205        $this->assertTrue( wp_next_scheduled( $hook ) > 0 );
     206        $this->assertTrue( wp_next_scheduled( $hook, $args ) > 0 );
     207
     208        // clear the schedule and make sure it's gone.
     209        wp_unschedule_hook( $hook );
     210        $this->assertFalse( wp_next_scheduled( $hook ) );
    190211    }
    191212
Note: See TracChangeset for help on using the changeset viewer.