You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce中实现优惠券每人每月使用次数限制自动重置

WooCommerce优惠券单用户每月使用1次实现方案

实现思路

  • 弃用WooCommerce原生的「Usage limit per user」永久限制参数,改为自定义校验逻辑
  • 记录每位用户使用优惠券的时间戳
  • 验证优惠券有效性时,判断用户近30天/自然月内是否有使用记录,有则判定不可用

代码实现

将以下代码添加到WordPress站点当前主题的functions.php文件末尾,或者自定义功能插件中即可生效:

// 记录用户使用优惠券的时间
add_action('woocommerce_coupon_used', 'record_coupon_usage_time', 10, 3);
function record_coupon_usage_time($coupon, $order, $user_id) {
    // 如只需限制特定优惠券,打开下方注释并修改优惠券代码
    // if($coupon->get_code() != 'discount40') return;
    
    if($user_id) {
        $usage_key = 'coupon_usage_' . $coupon->get_id();
        $usage_history = get_user_meta($user_id, $usage_key, true);
        if(!is_array($usage_history)) $usage_history = [];
        // 记录本次使用时间,可只保留最近1条减少数据库冗余
        $usage_history[] = time();
        update_user_meta($user_id, $usage_key, $usage_history);
    }
}

// 自定义优惠券有效性校验
add_filter('woocommerce_coupon_is_valid', 'check_monthly_coupon_usage_limit', 10, 3);
function check_monthly_coupon_usage_limit($is_valid, $coupon, $discount) {
    // 如只需限制特定优惠券,打开下方注释并修改优惠券代码
    // if($coupon->get_code() != 'discount40') return $is_valid;
    
    $user_id = get_current_user_id();
    if(!$user_id) return $is_valid; // 未登录用户按原生逻辑处理,可自行调整
    
    $usage_key = 'coupon_usage_' . $coupon->get_id();
    $usage_history = get_user_meta($user_id, $usage_key, true);
    
    if(is_array($usage_history) && !empty($usage_history)) {
        // 取最近一次使用时间,判断是否在30天内
        $last_usage = end($usage_history);
        if(time() - $last_usage < 30 * 86400) {
            wc_add_notice('该优惠券每位用户每月仅可使用1次,请下月再尝试', 'error');
            return false;
        }
    }
    return $is_valid;
}

自定义调整说明

  • 如需限制仅指定优惠券生效,取消代码中对应注释,将discount40替换为目标优惠券代码即可
  • 如需按自然月重置(如1月31日使用,2月1日即可复用),将代码中的时间判断逻辑替换为以下内容:
    $last_month = date('Ym', $last_usage);
    $current_month = date('Ym');
    if($last_month == $current_month) {
        wc_add_notice('该优惠券每位用户每月仅可使用1次,请下月再尝试', 'error');
        return false;
    }
    
  • 未登录用户的限制逻辑可根据需求自行调整,比如通过Cookie记录使用时间

内容的提问来源于stack exchange,提问作者ksaif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 16:36:01