Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a discount only on the second cart item in Woocommerce

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

like image 453
Bogdan Avatar asked Oct 24 '25 18:10

Bogdan


1 Answers

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.

like image 57
LoicTheAztec Avatar answered Oct 26 '25 07:10

LoicTheAztec