Apply a discount only on the second cart item in Woocommerce

喜你入骨 提交于 2019-12-08 07:51:18

问题


How to get and modify price of the second item in my cart?

I want to made discount -3% on the second product (items in cart already sorted by the price, highest top).

I think it must calculate in woocommerce_before_calculate_totals or like discount in woocommerce_cart_calculate_fees?

Thanks


回答1:


Updated (Added compatibility with Woocommerce 3+)

For a product item is better to use woocommerce_before_calculate_totals action hook:

add_action( 'woocommerce_before_calculate_totals', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Initialising
    $count = 0;
    $percentage = 3; // 3 %

    // Iterating though each cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        $count++;
        if( 2 == $count){ // Second item only
            $price = $cart_item['data']->get_price(); // product price
            $discounted_price = $price * (1 - ($percentage / 100)); // calculation

            // Set the new price
            $cart_item['data']->set_price( $discounted_price );
            break; // stop the loop
        }
    }
}

Or using a cart discount (negative cart fee):

add_action( 'woocommerce_cart_calculate_fees', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Initialising
    $count = 0;
    $percentage = 3; // 3 %

    // Iterating though each cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        $count++;
        if( 2 == $count){ // Second item only
            $price = $cart_item['data']->get_price(); // product price
            $discount = $price * $percentage / 100; // calculation
            $second_item = true;
            break; // stop the loop
        }
    }
    if( isset($discount) && $discount > 0 )
        $cart->add_fee( __("2nd item 3% discount", 'woocommerce'), -$discount );
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.



来源:https://stackoverflow.com/questions/45255375/apply-a-discount-only-on-the-second-cart-item-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!