Quantity discount on 2nd item only in Woocommerce

后端 未结 3 975
故里飘歌
故里飘歌 2021-01-16 04:41

I want to achieve a global discount for all products but only for the 2nd product item.

What do I mean? If the customer buys \"Jacket\" no discount is given.

3条回答
  •  花落未央
    2021-01-16 05:11

    You could use the Fee API to get a discount (20%) on the 2nd item only this way:

    add_action( 'woocommerce_cart_calculate_fees', 'second_item_discount', 10, 1 );
    function second_item_discount( $cart ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        $percentage = 20; // 20%
        $discount   = 0;
    
        // Loop through cart items
        foreach ( $cart->get_cart() as $cart_item ) {
            // When quantity is more than 1
            if( $cart_item['quantity'] > 1 ){
                // 20% of the product price as a discount
                $discount += wc_get_price_excluding_tax( $cart_item['data'] ) * $percentage / 100;
            }
        }
        if( $discount > 0 )
            $cart->add_fee( __( '2nd item discount', 'woocommerce' ) , -$discount );
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

提交回复
热议问题