Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
1  
Using cron aside, plugins should generally hook to the init hook. wp is used more internally. –  bungeshea May 31 '13 at 9:37

1 Answer 1

up vote 7 down vote accepted

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?

share|improve this answer
    
+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. –  Rilwis 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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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