首页 文章

优惠券根据Woocommerce中的产品类别提供2种不同的百分比折扣

提问于
浏览
1

我正在寻找一个Woocommerce钩子,它将有助于在应用特定优惠券时根据2种不同的产品类别限制更改折扣百分比 .

例如,如果客户添加特定优惠券,我想:

  • 如果购物车商品来自产品类别A,那么它将为该商品提供10%的折扣 .

  • 如果它在产品类别B中,它将为该项目提供20%的折扣

  • 更新总购物车价格

有没有可用于实现此目的的钩子?任何可用的动作挂钩或过滤钩?

到目前为止这是我的代码:

add_filter( 'woocommerce_get_discounted_price', 'apply_coupon', 10);
function apply_coupon($price) {
     global $woocommerce;
     $product=$woocommerce->cart->product;
     if(has_term( 'duplex-blinds', 'A' ,$product->id)){
       get_product_cart_price; 
      10% DISCOUNT
     }
     if(has_term( 'duplex-blinds', 'A' ,$product->id)){
      20% DISCOUNT
     }
     upadte total_discunt_incart($new_discount);
     upadte new_price_in_cart($new_price);
     upadte new_price_in_checkout($new_price);
  return $price;
}

重要的是我需要修改 total cart pricetotal checkout price ,总折扣价和折扣价需要发送到Paypal .

我的商店有许多钩子,这就是为什么商业默认优惠券计算会出错 . 我注意到在购物车页面中,折扣价格是根据自定义产品价格正确得出的,但它没有从原始购物车数量更新,因此总价格保持不变 .

但在结账页面折扣价格是根据产品原价而非产品定制价格计算的,所以折扣出错了,也不是从总价格中最小化...

1 回答

  • 5

    以下是一种完全不同的方法,使其有效...此答案代码将根据2个特定产品类别启用2个不同折扣百分比的优惠券代码 .

    例如,请说您的相关产品类别是:

    • 对于 10% 的优惠券折扣,产品类别slug将为 'hoodies'

    • 对于 20% 的优惠券折扣,产品类别slug将为 't-shirts'

    (您可以在代码中使用产品类别ID,slugs或Names)

    这将需要2个步骤:

    • 优惠券设置(正确设置优惠券代码):

    • 折扣类型: Percentage

    • 金额: 10

    • 限制>产品类别(显示的名称):"Hoodies"和"T shirts"
      enter image description here

    • 如果需要,您可以进行其他设置

    • 代码功能内的设置:

    • 优惠券代码:将您的优惠券代码设置为小写

    • 't-shirts' 产品类别slug(折扣的20%) .


    现在来了代码(您将添加设置):

    add_filter( 'woocommerce_coupon_get_discount_amount', 'alter_shop_coupon_data', 20, 5 );
    function alter_shop_coupon_data( $round, $discounting_amount, $cart_item, $single, $coupon ){
    
        ## ---- Your settings ---- ##
    
        // Related coupons codes to be defined in this array (you can set many)
        $coupon_codes = array('10percent');
    
        // Product categories at 20% (IDs, Slugs or Names)  for 20% of discount
        $product_category20 = array('hoodies'); // for 20% discount
    
        $second_percentage = 0.2; // 20 %
    
        ## ---- The code: Changing the percentage to 20% for specific a product category ---- ##
    
        if ( $coupon->is_type('percent') && in_array( $coupon->get_code(), $coupon_codes ) ) {
            if( has_term( $product_category20, 'product_cat', $cart_item['product_id'] ) ){
                $original_coupon_amount = (float) $coupon->get_amount();
                $discount = $original_coupon_amount * $second_percentage * $discounting_amount;
                $round = round( min( $discount, $discounting_amount ), wc_get_rounding_precision() );
            }
        }
        return $round;
    }
    

    代码位于活动子主题(或活动主题)的function.php文件中 . 经过测试和工作 .


    这是一个插图实际工作示例(带屏幕截图):

    enter image description here

    enter image description here

    • 第一个购物车项目(来自 'hoodies' 产品类别)获得10%的折扣 $40 x 10% = $4

    • 第二个购物车项目(来自 't-shirts' 产品类别)获得折扣的20% $30 x 20% = $6

    所以总折扣是 $4 + $6 = $10 ......那很有效!

相关问题