0

Is it possible to set up new wp_cron jobs dynamically upon a certain action?

I have a form submission (I'm using Gravity Forms, so have several functions set up on several of their hooks already) process which creates a post of a specific post type when a user completes and submits the form.

What I'd like to do is set up a cron job when this submission happens. Each form submission will set up a new cron event (don't worry they'll get cleared after a certain amount of time, normally within 48 hours).

My understanding is that when you use wp_schedule_event() you're basically creating a new action hook, which you then hook into with a custom function. So in essence I need to dynamically create a new hook (which needs to be unique for each) and then a custom function for each (again, unique).

i.e. something like

function lmk_alter_method_name( $entry, $form )
{

    //.... some code (which sets up a $post object) ...

    wp_update_post( $post );

    //Call some dynamic wp_cron -related thing here
    lmk_set_up_cron( $post->ID );

}

add_action( 'gform_after_submission', 'lmk_alter_method_name', 10, 2 );



function lmk_set_up_cron( $post_id )
{

    if( !wp_next_scheduled( 'lmk_cron_' . $post_id ) )
        wp_schedule_event( time() + 3600, 'hourly', 'lmk_cron_' . $post_id, $post_id );

}

The idea there is that it'll create a hook called lmk_cron_123 but that then how do I go about actually hooking into that, dynamically.

I'm convinced there's an easier way, but I can't quite see it at the moment. Any suggestions?

1 Answer 1

2

A simple and dynamic way to use WordPress cron would be to set up an action hook for your schedule then only add scheduled events as and when you need them. The events would call a generic function and pass in your specific custom post type details through $args -

add_action('my_schedule_event', 'generic_function');

function set_schedule($post_id) {
    $time = strtotime(date('Y-m-d H') . ':00:00');      
    $args = array('post_id' => $post_id);        
    wp_schedule_event( $time, 'hourly', 'my_schedule_event', $args);
}

function generic_function($post_id) {
    // do your thing
}

So in lmk_alter_method_name() you call set_schedule($post_id).

Hope that helps!

1
  • I'm such an idiot. That makes complete sense. Thanks a lot Iain. Commented Dec 30, 2012 at 20:29

Your Answer

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

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