购物车中没有促销商品时,第二项商品的Woocommerce折扣

时间:2018-12-25 18:03:50

标签: php wordpress woocommerce cart discount

现在我有以下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%的折扣?

当我有两个商品到第二个商品时,如何才能只为不在销售中的商品增加折扣?

1 个答案:

答案 0 :(得分:0)

如果购物车中没有出售的商品,以下商品将为第二种商品提供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文件中。经过测试,可以正常工作。