WooCommerce中的优惠券类型

WooCommerce中默认有三种优惠券类型。

  1. 固定金额折扣(Fixed Cart Discount):按固定金额减免订单总金额。
  2. 百分比折扣(Percentage Discount):按订单总金额的一定百分比减免金额。
  3. 固定金额折扣(Fixed Product Discount):按固定金额减免特定产品的价格。

可以使用 woocommerce_coupon_discount_types 这个钩子来添加自定义的折扣类型。下面是一个示例代码:

// 添加自定义折扣类型
function custom_coupon_discount_type($types) {
    // 添加新的折扣类型
    $types['fixed_category'] = __('Fixed Category Discount', 'your-text-domain');
    $types['percent_category'] = __('Percentage Category Discount', 'your-text-domain');
    
    return $types;
}
add_filter('woocommerce_coupon_discount_types', 'custom_coupon_discount_type', 10, 1);

上述代码通过 woocommerce_coupon_discount_types 这个钩子,将两个自定义的折扣类型 fixed_categorypercent_category 添加到折扣类型列表中。你可以根据自己的需求修改折扣类型的名称和标识符。

请将上述代码添加到你的主题的 functions.php 文件或自定义插件中。在添加完代码后,你可以在创建或编辑优惠券时看到新添加的折扣类型选项。

上面只是添加好,还没写优惠策略。我们可以通过这个钩子来写woocommerce_before_calculate_totals。

// 在计算订单总金额前应用优惠券折扣
function apply_coupon_discount($cart) {
    if (is_admin() && !defined('DOING_AJAX')) {
        return;
    }
    
    if (empty(WC()->cart) || !is_a(WC()->cart, 'WC_Cart')) {
        return;
    }
    
    // 检查是否有优惠券应用于购物车
    if (!WC()->cart->has_discount()) {
        return;
    }
    
    // 获取应用的优惠券对象
    $applied_coupons = WC()->cart->get_applied_coupons();
    
    foreach ($applied_coupons as $coupon_code) {
        $coupon = new WC_Coupon($coupon_code);
        
        // 检查优惠券类型是否为你想要的类型
        if ($coupon->get_discount_type() == 'fixed_category') {
            // 根据你的逻辑应用固定金额折扣
            // 可以使用 `$coupon->get_amount()` 获取折扣金额
            // 可以使用 `$coupon->get_categories()` 获取适用的产品分类
        } elseif ($coupon->get_discount_type() == 'percent_category') {
            // 根据你的逻辑应用百分比折扣
            // 可以使用 `$coupon->get_amount()` 获取折扣百分比
            // 可以使用 `$coupon->get_categories()` 获取适用的产品分类
        }
    }
}
add_action('woocommerce_before_calculate_totals', 'apply_coupon_discount', 10, 1);
© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称常用语 夸夸
夸夸
还有吗!没看够!
表情代码图片

    暂无评论内容