6

Which one do you recommend using within a plugin and why?

add_action( 'wp', 'trigger_me' );
function trigger_me() {

    if ( !wp_next_scheduled( 'my_plugin_cron' ) ) {
        wp_schedule_event(time(), 'hourly', 'my_plugin_cron');
    }

}

OR

add_action( 'init', 'trigger_me' );
function trigger_me() {

    if ( !wp_next_scheduled( 'my_plugin_cron' ) ) {
        wp_schedule_event(time(), 'hourly', 'my_plugin_cron');
    }

}

What are the advantages/disadvantages of "wp" over "init" when registering/triggering cron function within a plugin?

1
  • 2
    Using cron aside, plugins should generally hook to the init hook. wp is used more internally.
    – shea
    May 31, 2013 at 9:37

1 Answer 1

9

Neither.

register_activation_hook( __FILE__, 'trigger_me' );

function trigger_me() {

    if ( !wp_next_scheduled( 'my_plugin_cron' ) ) {
        wp_schedule_event(time(), 'hourly', 'my_plugin_cron');
    }

}

Why parse code on every request when you don't need to?

5
  • +1 Might seem small, but a few of these can add up quick. May 23, 2013 at 22:27
  • 1
    Should probably also unschedule it on deactivation, codex.wordpress.org/Function_Reference/wp_unschedule_event May 23, 2013 at 23:45
  • While this is a correct "design" for adding cron in WP, it still have problem in some cases like: updating plugin version (trigger doesn't happen because the plugin has been activated), or in development stage when you modify the plugin code. Using init or wp hook may not be the "right" approach, but it solves these problems.
    – Anh Tran
    May 29, 2013 at 2:24
  • Plugins are deactivated/reactivated on update through admin. The fact that a plugin is in development is no excuse for poor coding.
    – vancoder
    May 29, 2013 at 16:04
  • 1
    This is correct answer, but what about using inside theme ? Dec 14, 2016 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.