【问题标题】:Woocommerce discount on second item when not on sale items are in cart购物车中未销售商品时,第二件商品的 Woocommerce 折扣
【发布时间】:2018-12-25 18:03:50
【问题描述】:

现在我有以下 Woocommerce 折扣:1) 一件商品 --> 10% 仅适用于非特价商品 2) 两件商品 20% 用于最便宜的商品,包括特价商品

我尝试使用Cart discount based on cart item count and only for items that are not in saleCart discount for product that cost less in Woocommerce 回答代码。

当我有两件商品时,如何为第二件商品添加 10% 的折扣?

当我有两件商品时,如何仅将非特价商品的折扣添加到第二件商品?

【问题讨论】:

    标签: php wordpress woocommerce cart discount


    【解决方案1】:

    当购物车中没有在售商品时,以下将在第 2 件商品上享受 10% 的折扣:

    add_action('woocommerce_cart_calculate_fees' , 'custom_2nd_item_discount', 10, 1);
    function custom_2nd_item_discount( $cart ){
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Only for 2 items or more
        if ( $cart->get_cart_contents_count() < 2 )
            return;
    
        // Initialising variable
        $has_on_sale = false;
        $count_items = $discount = 0;
        $percentage  = 10; // 10 %
    
        // Iterating through each item in cart
        foreach( $cart->get_cart() as $cart_item ){
            $count_items++;
            if( $cart_item['data']->is_on_sale() ){
                $has_on_sale = true;
            }
            if( 2 == $count_items ){
                $discount = wc_get_price_excluding_tax( $cart_item['data'] ) * $percentage / 100;
            }
        }
    
        // Apply discount to 2nd item for non on sale items in cart
        if( ! $has_on_sale && $discount > 0 )
            $cart->add_fee( sprintf( __("2nd item %s%% Discount"), $percentage), -$discount );
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。

    【讨论】:

      猜你喜欢
      • 2020-08-18
      • 2017-06-05
      • 1970-01-01
      • 2019-06-28
      • 2020-11-24
      • 2019-01-31
      • 2019-02-06
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多