1
votes

First of all, I have several simple products in my Woocommerce shop. If a customer takes 2 pieces of one product, the price should not double. Instead Product A costs 40 for 1 piece and if the customer wants a second piece it should cost 20 - so overall 60. Product B - 1 unit costs 25 and 2 units should costs 40 in total for example.

I have tried to add an absolute value to the cart total, but even this does not work (found this code on stackoverflow).

  function add_discount_price_absolute( $cart_object ) {
    global $woocommerce;
    $custom_discount_absolute = 15; // custom discount percent
    $pdtcnt=0;

    foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
        $pdtcnt++;
        if($pdtcnt>1) { // from second product
            $oldprice = $cart_item['data']->price; //original product price
            $newprice = $oldprice + $custom_discount_absolute; //discounted price
            $cart_item['data']->set_price($newprice);
        }        
    }
}

add_action( 'woocommerce_before_calculate_totals', 'add_discount_price_absolute' );

Would really appreciate your help. Thanks

1

1 Answers

0
votes

You can make use of woocommerce_before_calculate_totals hook

function add_discount_price_absolute( $cart_object ) {  
    $new_price = 20;

    foreach ($cart_object->cart_contents as $key => $cart_item ) {          
        $product = wc_get_product( $cart_item['product_id'] );
        $productcount = $cart_item['quantity'];
        
        //echo '<pre>', print_r($cart_item, 1), '</pre>';
        
        if( $productcount > 1) { // from second product 
            $cart_item['data']->set_price( $new_price );
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'add_discount_price_absolute', 10, 1 );