4

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
    Using cron aside, plugins should generally hook to the init hook. wp is used more internally. – shea May 31 '13 at 9:37
7

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?

  • +1 Might seem small, but a few of these can add up quick. – Andrew Bartel May 23 '13 at 22:27
  • Should probably also unschedule it on deactivation, codex.wordpress.org/Function_Reference/wp_unschedule_event – Matthew Boynes May 23 '13 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 '13 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 '13 at 16:04
  • This is correct answer, but what about using inside theme ? – Goran Jakovljevic Dec 14 '16 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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