Получить процент налога на товары заказа в WooCommerce

Для заказа я хотел бы получить для каждого товара процент налога (например: 20%), но WooCommerce возвращает только расчетные значения.

Мне нужно, чтобы он позаботился о опции WooCommerce «Рассчитать налог на основе» (для каждого случая: «Базовый адрес магазина», «Адрес выставления счета клиента» и «Адрес доставки клиента»).

Я пробовал разные коды, но ни один из них не дает хорошего результата:

1) Возвращенный процент не зависит от местоположения клиента.

$order = wc_get_order($orderId);

foreach ($order->get_items() as $item) {
    $product = $item->get_product();

    $tax = new WC_Tax();
    $taxes = $tax->get_rates($product->get_tax_class());
    $rates = array_shift($taxes);

    var_dump($rates);
    // array(4) { ["rate"]=> float(20) ["label"]=> string(3) "TVA" ["shipping"]=> string(3) "yes" ["compound"]=> string(2) "no" } 
}

2) Не возвращает налог для каждого продукта.

$order = wc_get_order($orderId);

foreach ($order->get_items('tax') as $tax_item) {
    var_dump($tax_item->get_data());
    // array(11) { ["id"]=> int(457) ["order_id"]=> int(143) ["name"]=> string(0) "" ["rate_code"]=> string(8) "BE-TVA-1" ["rate_id"]=> int(4) ["label"]=> string(3) "TVA" ["compound"]=> bool(false) ["tax_total"]=> string(2) "66" ["shipping_tax_total"]=> int(0) ["rate_percent"]=> float(75) ["meta_data"]=> array(0) { } } 
}

3) Вернуть пустой массив

$order = wc_get_order($orderId);

foreach ($order->get_items() as $item_id => $item) {
    $product = $item->get_product();
    $taxes = WC_Tax::get_rates_from_location($product->get_tax_class(), [
        'country' => $order->get_billing_country(),
        'state' => $order->get_billing_state(),
        'postcode' => $order->get_billing_postcode(),
        'city' => $order->get_billing_city(),
    ]);

    var_dump($taxes);
    // array(0) { }
}

Я также пытался выполнить математические вычисления, чтобы получить проценты, но иногда получаю противоречивые значения (например: 5,51111%) и не могу их использовать, потому что они будут отправлены в API, которому нужны действительные значения процентов.

Как убрать количество товаров в категории WooCommerce
Как убрать количество товаров в категории WooCommerce
По умолчанию WooCommerce показывает количество товаров рядом с категорией, как показано ниже.
1
0
79
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Вы можете попробовать следующее, чтобы получить процент налога для каждой позиции заказа:

$order     = wc_get_order($order_id); // Get WC_Order object from order ID
$tax_rates = array(); // Initializing

// Loop through order tax items
foreach ( $order->get_items('tax') as $item ) {
    $tax_rates[$item->get_rate_id()] = $item->get_rate_percent();
}

// Loop through order line items
foreach ( $order->get_items() as $item ) {
    $item_taxes   = $item->get_taxes(); // Get item taxes array
    $tax_rate_id  = current( array_keys($item_taxes['subtotal']) );

    $tax_percent  = $tax_rates[$tax_rate_id]; // The tax percentage for the current item
    echo '<pre>Tax percentage: '. print_r($tax_percent, true ) . '%</pre>';
    
    $tax_subtotal = $item_taxes['subtotal'][$tax_rate_id]; // item tax subtotal (non rounded)
    $tax_total    = $item_taxes['total'][$tax_rate_id]; // item tax total (coupon discounted, non rounded)
    echo '<pre>Tax subtotal: '. print_r($tax_subtotal, true ) . '</pre>';
    echo '<pre>Tax total (discounted): '. print_r($tax_total, true ) . '</pre>';
}

Спасибо, я не подумал сопоставить промежуточные ключи элементов со списком налогов.

fdehanne 26.03.2024 09:17

Другие вопросы по теме