仅在Woocommerce中的第二个项目有数量折扣

时间:2019-01-19 11:11:20

标签: php wordpress woocommerce cart discount

我想为所有产品实现全球折扣,但仅限于第二个产品。

我是什么意思? 如果客户购买“夹克”,则不会给予折扣。

客户购买两种“夹克”产品。第二个“夹克”提供20%的折扣。

客户购买五种“夹克”产品。第二个“夹克”仍仅可享受20%的折扣。

它对所有简单和可变产品均适用。

我设法弄清楚了这件事,我正在寻求有关如何使折扣仅适用于第二项的帮助。

代码如下:

add_filter('woocommerce_product_get_price', 'fifty_percent_on_second_product', 90, 2 );
add_filter('woocommerce_product_get_regular_price', 'fifty_percent_on_second_product', 90, 2 );
function fifty_percent_on_second_product( $price, $product ) {
    if ( is_user_logged_in() ) { 

        I do not know what to do here

}   
    return $price;   
}

有人知道如何进行这项工作吗?如果是这样,请帮助我。

3 个答案:

答案 0 :(得分:1)

您只能通过以下方式使用Fee API获得第二项折扣(20%):

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 );
}

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

答案 1 :(得分:0)

add_action( 'woocommerce_before_calculate_totals', 'set_the_discount' );

function set_the_discount( $cart ) {

foreach ( $cart->cart_contents as $key => $value ) {    

    //please check whether your item is the second item of your cart or not?

    //if this is your second item in your cart

    //Set the 50% discount

    $product_id = $value['product_id'];
    $product = wc_get_product($product_id);
    $get_price = $product->get_price();
    $new_price = $get_price / 2;
    $value['data']->set_price($new_price);
  }

}
This hook can be used to set the price directly to the cart. Hope this may help

答案 2 :(得分:0)

foreach ( $cart->cart_contents as $key => $values ) {
                    $product_id = $values['product_id'];

                    foreach ($cart->get_cart_item_quantities() as $key => $value){
                        //print_r($key[1]);
                        $key = array_keys($cart->get_cart_item_quantities())[1];
                        if($key == $product_id){

                            $product = wc_get_product($product_id);
                            $get_price = $product->get_price();
                            $new_price = $get_price / 2;
                            $values['data']->set_price($new_price);

                            break;
                        }
                    }
                }
//Please try this, it will work for sure in same above hook :)