Мне нужно добавить новый налог в размере 8 % перед общей ценой к определенным продуктам только для определенной роли «различный_пользователь».
Другие продукты уже включают в себя другие налоги, которые указаны перед окончательной ценой, а затем добавляются к ней.
Важно, чтобы этот налог не влиял на другие налоги или скидки. уже добавлен в WooCommerce.
Impuesto
2,20
€
Мне удалось добавить налог к нужным мне продуктам с помощью add_action через их «ID», и это работает.
Но это показано в другой строке:
Ajuste de impuestos adicionales
0,38€
Как мне добавить этот налог к тем налогам, которые у меня уже есть в WooCommerce, а не показывать в новой строке?
У меня есть пробовал несколько раз, но меня это очень смущает, я не могу понять, как WooCommerce работает с налогами.
Я мог бы напрямую добавить новую ставку налога в WooCommerce, но поскольку это только наверняка продукты, я не могу этого сделать, и меня заблокировали
Вот результат:

// 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, '' );
}
}
/////////// РЕДАКТИРОВАТЬ ЗАПРОС:
РЕДАКТИРОВАТЬ ЗАПРОС:
Это возможное решение, но я не уверен.
Я тестировал его в тестовой среде, оно работает, но не знаю, будет ли оно совместимо с другие скидки и налоги, которые указаны на моем сайте.
Надеюсь, вы мне поможете.
Вот возможное решение:
// 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 'usuario_diferente' role
if (!current_user_can('usuario_diferente')) {
return;
}
// IDs of products that should receive the 8% tax
$product_ids_with_tax = array(966, 301, 328, 326, 327, 355, 625); // Sustituir con los IDs reales de los productos
// 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
}
}
// Si hay un monto de impuesto a agregar, o no hay otros impuestos presentes
if ($tax_amount > 0) {
// Get current taxes
$taxes = WC()->cart->get_cart_contents_taxes();
// If taxes already exist, add the additional tax
if (!empty($taxes)) {
foreach ($taxes as $key => $value) {
$taxes[$key] += $tax_amount;
break; // We only modified the first tax found
}
} else {
// If there is no tax, we add the tax as the first one
$cart->add_fee(__('Impuesto', 'woocommerce'), $tax_amount, true); // Lo marcamos como impuesto
}
// Set modified taxes if there were already taxes
if (!empty($taxes)) {
WC()->cart->set_cart_contents_taxes($taxes);
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... oocommerce