【问题标题】:WooCommerce specific coupon discount based on product category基于产品类别的 WooCommerce 特定优惠券折扣
【发布时间】:2021-06-10 18:32:13
【问题描述】:

我在使用此代码时遇到问题,无法对不同类别的产品应用不同百分比的折扣

该功能有效,但执行 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;
}

【问题讨论】:

    标签: php wordpress woocommerce cart coupon


    【解决方案1】:

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

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

    尝试以下方法:

    add_filter( 'woocommerce_coupon_get_discount_amount', 'alter_shop_coupon_data', 100, 5 );
    function alter_shop_coupon_data( $discount, $discounting_amount, $cart_item, $single, $instance ){
        // Loop through applied WC_Coupon objects
        foreach ( WC()->cart->get_coupons() as $code => $coupon ) {
            if ( $coupon->is_type('percent') && $coupon->get_code() == 'newsite' ) {
                $discount = $cart_item['data']->get_price() * $cart_item['quantity'];
     
                if( has_term( 'cat1', 'product_cat', $cart_item['product_id'] ) ){
                    $discount *= 0.2; // 20%
                }else{
                    $discount *= 0.1; // 10%
                }
            }
        }
        return $discount;
    }
    

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

    【讨论】:

      猜你喜欢
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 2012-12-27
      相关资源
      最近更新 更多