Add new tax to WooCommerce tax rates for certain products

I have a problem with WooCommerce taxes. I need to add a new 8% tax before the total price to certain products only for a specific role, 'different_user'. Other products already include other taxes that are shown before the final price, and then added to it. It is important that this tax does not affect any other taxes or discounts already added to WooCommerce. <tr class="tax-rate tax-rate-impuesto-1"> <th>Impuesto</th> <td data-title="Impuesto"> <span class="woocommerce-Price-amount amount">2,20 <span class="woocommerce-Price-currencySymbol">€</span> </span> </td> </tr> I have managed to add the tax to the products I need using add_action through their "ID", and it works. But it is shown on a different line: <tr class="fee"> <th>Ajuste de impuestos adicionales</th> <td data-title="Ajuste de impuestos adicionales"> <span class="woocommerce-Price-amount amount"> <bdi>0,38<span class="woocommerce-Price-currencySymbol">€</span> </bdi> </span> </td> </tr> How should I make this tax be added to the ones I already have from WooCommerce, instead of being shown on a new line? I have tried several times, but I am really confused about this, I cannot understand how WooCommerce works with taxes. I could directly add a new tax rate in WooCommerce, but since it is only for certain products, I cannot do it and I am blocked This is the result: // Hook to modify taxes based on products and user roles add_action('woocommerce_cart_calculate_fees', 'add_custom_tax_to_selected_products', 20, 1); function add_custom_tax_to_selected_products($cart) { // Check if it is admin or AJAX request, and avoid executing the code in that case if (is_admin() && !defined('DOING_AJAX')) { return; } // Check if the user has the role 'different_user' if (!current_user_can('usuario_diferente')) { return; } // IDs of products that should receive the 8% tax $product_ids_with_tax = array(355, 625); // Variable to store the total additional tax $tax_amount = 0; //Iterate over the products in the cart foreach ($cart->get_cart() as $cart_item_key => $cart_item) { $product_id = $cart_item['product_id']; // Check if the product is on the list of products with additional tax if (in_array($product_id, $product_ids_with_tax)) { //Calculate 8% of the subtotal of this product $item_total = $cart_item['line_total']; // Total price of the product in the cart without taxes $tax_amount += ($item_total * 0.08); // Add 8% of the total price of that product } } // If there is a tax amount to add, we add it to the total taxes if ($tax_amount > 0) { $cart->add_fee( __('Ajuste de impuestos adicionales', 'woocommerce'), $tax_amount, true, '' ); } }

Comment (0)

You’ll be in good company