This question already has answers here:
Answer
Solution:
Figured it out.
Have to edit the foreach to foreach($items as $cart_item_key => $item)
, and then use WC()->cart->set_quantity( $cart_item_key, 1 );
.
Here's the full code:
add_action( 'woocommerce_before_calculate_totals', 'change_price_of_product' );
function change_price_of_product() {
$items = WC()->cart->get_cart();
$coupons = WC()->cart->applied_coupons;
$only_one_gift = 0;
if (in_array('getmygift', $coupons)) {
foreach($items as $cart_item_key => $item) {
if (isset($item['product_id'])) {
if ($only_one_gift > 0) {
break;
}
if (($item['product_id']) == 5261) {
$only_one_gift++;
$item['data']->set_price( 0 );
WC()->cart->set_quantity( $cart_item_key, 1 );
}
}
}
}
}
Source