I would like to set the price of individual products to 0 in the checkout when a specific payment method is selected. My code sets the price of these products to 0 and the subtotal is calculated correctly. However, the taxes and the total sum are wrong. Woocommerce assumes that the price has not changed.
Can someone check this code and find the error?
function update_product_prices_and_totals($cart_object) {
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
if (is_checkout() && isset($_POST['payment_method']) && $_POST['payment_method'] === 'invoice') {
// Set subtotal, tax, and total to 0
$subtotal = 0;
$total = 0;
$included_products = array(338991, 353754); // Array of product IDs to include
// Loop through the products in the cart
foreach ($cart_object->get_cart() as $cart_item_key => $cart_item) {
$product_id = $cart_item['product_id'];
// Check the product IDs
if (in_array($product_id, $included_products)) {
// Set the price to 0
$cart_item['data']->set_price(0);
// Calculate taxes for this product and subtract from the subtotal
$taxes = array_sum($cart_item['line_tax_data']['subtotal']);
$subtotal -= $taxes;
continue; // Skip the iteration for included products
}
// Update the subtotal
$subtotal += $cart_item['line_subtotal'];
}
// Update the total
$total = $subtotal + $cart_object->get_cart_contents_tax();
// Set the updated subtotal and total
$cart_object->subtotal = $subtotal;
$cart_object->total = $total;
}
}
add_action('woocommerce_cart_calculate_fees', 'update_product_prices_and_totals', 10, 1);
I have tried to change the total and the taxes from Woocommerece methods. A better way would be to set the taxes for these products directly to 0, which also did not work.