I am trying to apply discounts based on quantity amounts in the cart for each product. Each product has it's own quantity discounts set by custom fields. I'm using the action "woocommerce_before_calculate_totals" and in the foreach loop trying to apply the discount from the custom fields. However, it only works for the first item in the cart. The second item is set at the full price. I can't see why it doesn't work for the rest of the items in the cart.
Here is my current code:
add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_price', 20, 1 );
function set_custom_cart_item_price( $wc_cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// First loop to check if product 11 is in cart
foreach ( $wc_cart->get_cart() as $key => $cart_item ){
// This is necessary for WC 3.0+
$qty = $cart_item['quantity'];
$discount1 = get_post_meta($cart_item['product_id'], '_discount_1_4_items', true);
$discount2 = get_post_meta($cart_item['product_id'], '_discount_5_9_items', true);
$discount3 = get_post_meta($cart_item['product_id'], '_discount_10_19_items', true);
$discount4 = get_post_meta($cart_item['product_id'], '_discount_20_items', true);
$OriginalPrice = $cart_item['data']->get_price();
if($qty >= 1 && $qty <=4){
$FinalPrice = $OriginalPrice*$discount1;
}elseif($qty >= 5 && $qty <=9){
$FinalPrice = $OriginalPrice*$discount2;
}elseif($qty >= 10 && $qty <=19){
$FinalPrice = $OriginalPrice*$discount3;
}elseif($qty >= 20 ){
$FinalPrice = $OriginalPrice*$discount4;
}
$cart_item['data']->set_price( $FinalPrice );
}
}