在 WooCommerce 中指定时间后重置优惠券使用限制

问题描述 投票:0回答:1

所以基本上在 WooCommerce 中,我想在一小时的间隔后定期重置优惠券“usage_limit”和“usage_limit_per_user”。但是,我做不到。

我尝试了以下方法:

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' );
}

但这不起作用。

这里,只是为了测试它是否有效,我将计划时间设置为 60 秒。

任何帮助将不胜感激。

php wordpress woocommerce scheduled-tasks coupon
1个回答
0
投票

你没有以正确的方式这样做:

  • 对于
    'init'
    函数在指定时间触发的计划事件,您需要将
    wp_schedule_single_event()
    钩子替换为自定义命名钩子。
  • 相关
    add_action()
    始终位于使用
    wp_schedule_single_event()
    的函数之外。
  • 您还需要检查是否有任何优惠券使用限制处于活动状态。
  • 不要使用
    save_post
    钩子,因为它是所有 WordPress 帖子类型使用的通用钩子,并且会在更新优惠券数据之前触发。
    始终尝试使用专用的 WooCommerce 挂钩。
  • 始终尝试使用
    WC_Coupon
    getter 和 setter 方法
    (或
    WC_Data
    方法
    )而不是 WordPress
    get_post_meta()
    add_post_meta()
    update_post_meta()
    delete_post_meta()
    泛型函数。

尝试以下(未经测试)

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();
}

应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.