So basically in WooCommerce, I would like to reset coupon 'usage_limit' and 'usage_limit_per_user', after an hour of interval periodically. But, I'm unable to do that.
I tried the following:
add_action( 'save_post', $this,'reset_usage_limit' );
function reset_usage_limit() {
add_action( 'init', 'custom_delete_coupon_meta_function' );
wp_schedule_single_event( time() + 60, 'init', array( $coupon_id ) );
}
function custom_delete_coupon_meta_function( $coupon_id ) {
delete_post_meta( $coupon_id, 'usage_limit' );
delete_post_meta( $coupon_id, 'usage_limit_per_user' );
}
But it doesn't work.
Here, just to test if it is working or not, I have set the schedule time to 60 seconds.
Any help will be appreciated.
You are not doing that in the right way:
'init'hook by a custom named hook for the scheduled event triggered bywp_schedule_single_event()function at the specified time.add_action()is always outside the function usingwp_schedule_single_event().save_posthook as it is a generic hook used by all WordPress post types and also it is triggered before coupon data is updated.Always try to use dedicated WooCommerce hooks instead.
WC_Coupongetter and setter methods (orWC_Datamethods) instead of WordPressget_post_meta(),add_post_meta(),update_post_meta()ordelete_post_meta()generic functions.Try the following (untested):
It should work.
Now, you should know that WordPress scheduled task are not very reliable.
You should consider using Action Scheduler plugin instead, as it is a scalable and traceable job queue for background processing.
Note that Action Scheduler library is included and used by WooCommerce and WooCommerce Subscriptions. The documentation is available on ActionScheduler.org