基于产品类别的 WooCommerce 特定优惠券折扣

问题描述

代码有问题,无法对不同类别的产品应用不同百分比的折扣

函数工作但执行 n 次,其中 n 取决于购物车中的产品数量

add_filter( 'woocommerce_coupon_get_discount_amount','alter_shop_coupon_data',1,5 );
function alter_shop_coupon_data( $discount,$discounting_amount,$cart_item,$single,$instance ){
    $coupons = WC()->cart->get_coupons();
    $cart_items = WC()->cart->get_cart();

    foreach ( $coupons as $code => $coupon ) {
        if ( $coupon->discount_type == 'percent' && $coupon->code == 'newsite' ) {
            foreach ($cart_items as $cart_item){
                $product_id = $cart_item['data']->id;                 
                
                if( has_term( 'cat1','product_cat',$product_id ) ){
                    $quantity = $cart_item['quantity'];
                    $price = $cart_item['data']->price;
                    $discount_20 = 0.2 * ($quantity * $price); //  20%

                }else{
                    $quantity = $cart_item['quantity'];
                    $price = $cart_item['data']->price;
                    $discount_10 = 0.1 * ($quantity * $price); //10%
                }
            }
        }
    }
    $discounting_amount = ($discount_20 + $discount_10);
    return $discounting_amount;
}

解决方法

从 WooCommerce 3 开始,您的代码中有很多错误……而且 c = c + 1 参数包含在函数中,因此您无需遍历购物车项目。

另请注意,$cart_item (coupon type) 不是必需的,因为您在代码中定位了特定的优惠券:$coupon->is_type('percent')

尝试以下操作:

$coupon->get_code() == 'newsite

代码位于活动子主题(或活动主题)的functions.php 文件中。它应该会更好地工作。