Search code examples
phpwordpresswoocommercescheduled-taskscoupon

Reset coupon usage limit after a specified time in WooCommerce


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.


Solution

  • You are not doing that in the right way:

    • You need to replace 'init' hook by a custom named hook for the scheduled event triggered by wp_schedule_single_event() function at the specified time.
    • Related add_action() is always outside the function using wp_schedule_single_event().
    • You need also to check if any coupon usage limits is active, before.
    • Don't use save_post hook 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.
    • Always try to use WC_Coupon getter and setter methods (or WC_Data methods) instead of WordPress get_post_meta(), add_post_meta(), update_post_meta() or delete_post_meta() generic functions.

    Try the following (untested):

    add_action( 'woocommerce_coupon_options_save', 'trigger_coupon_schedule_single_event', 10, 2 );
    function trigger_coupon_schedule_single_event( $post_id, $coupon ) {
        // Check that some usage limit has been activated for the current coupon
        if ( $coupon->get_usage_limit() || $coupon->get_usage_limit_per_user() ) {
            // Create a shedule event on 'coupon_schedule_reset_restrictions' custom hook
            wp_schedule_single_event( time() + 60, 'coupon_schedule_reset_restrictions', array( $coupon ) );
        }
    }
    
    add_action( 'coupon_schedule_reset_restrictions', 'coupon_reset_restrictions' );
    function coupon_reset_restrictions( $coupon ){
        $coupon->set_usage_limit(null);
        $coupon->set_usage_limit_per_user(null);
        $coupon->save();
    }
    

    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