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.

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?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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!

share|improve this answer
    
I'm such an idiot. That makes complete sense. Thanks a lot Iain. –  RichardTape Dec 30 '12 at 20:29

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.