I'm making custom Wordpress plugin and did a simple form:
<form action="" method="post">
<input type="submit" name="button_update_products" value="Update">
</form>
...
...
if (isset($_REQUEST['button_update_products'])) :
add_action('admin_head', function () {wp_schedule_single_event(time() 50,'t_cron_now');});
add_action('t_cron_now', function () {...do something});
endif;
When I run this code and click button "Update" Wordpress is creating 't_cron_now' hook and scheduling it with 50 sec delay. But it doesn't attach second function to this hook. I'm checking this behavior with Crontrol plugin and it's very weird .
However if I slightly modify code to this:
if (isset($_REQUEST['button_update_products'])) :
add_action('admin_head', function () {wp_schedule_single_event(time() 50,'t_cron_now');});
endif;
add_action('t_cron_now', function () {...do something});
All works fine.
t_cron_now hook is created and function is attached to this hook.
I can't figure out why is this happening? And why I should move:
add_action('t_cron_now', function () {...do something});
outside of if (isset($_REQUEST['button_update_products'])) : statement to make this work? Could someone make sense for me of this behavior?
CodePudding user response:
wp_schedule_single_event()
schedules a hook which will only be triggered at the time specified.
add_action()
registers an action to be run when the specified hook is called, but it only registers it for the current request.
So when the time to fire the hook scheduled, if $_REQUEST['button_update_products']
is not set, which it wouldn't be in the request except if you submit the form again, WordPress will not find the action to fire.
But if you add it outside of the if statement, WP registers the action on every page request, and will only fire when the schedule triggers it.
So there is no issue in putting it outside of the if statement as long as the scheduler is within the if statement.