WooCommerce:仅从税率降低的商品中获取订单总额

问题描述

我只想导出税率降低的商品的总计。

例如,我有 2 件商品的税率降低了,一件商品的税率正常:

  • 项目 A:100 欧元 - 减税 5,00 欧元 - 总计 105,00 欧元
  • 项目 B:50 欧元 - 减税 2.50 欧元 - 总计 52.50 欧元
  • 项目 C:100 欧元 - 19,00 欧元正常税 - 总计 119,00 欧元

我现在想要项目 A 和 B 的总计。在本例中,合计值为 157,50 欧元。

我找到了一个 code snippet获取类的总税额:

// Get the WC_Order instance Object from the Order ID (if needed)
$order = wc_get_order($order_id);

// Output the tax rows in a table
echo '<table>';
foreach ( $order->get_tax_totals() as $rate_code => $tax ) {
    $tax_rate_id  = $tax->rate_id;
    $tax_label    = $tax->label;
    $tax_amount   = $tax->amount;
    $tax_f_amount = $tax->formatted_amount;
    $compound     = $tax->is_compound;
    echo '<tr><td>' . $tax_label  . ': </td><td>' . $tax_f_amount . '</td></tr>';
}
echo '</table>';

但该代码为我提供了所有税种。有没有办法只得到一个

这是我现在正在做的事情(摘录):

$custom_order_total_tax         = $custom_order_data['total_tax'];
$custom_order_total             = $custom_order_data['total'];      
$custom_order_subtotal          = $order->get_subtotal();

我不能在 $order 变量中使用任何东西。

我想我需要检查订单的所有项目。但我如何按税率选择这些项目?

我发现了一些东西here

// Get and Loop Over Order Items
foreach ( $order->get_items() as $item_id => $item ) {
   $product_id = $item->get_product_id();
   $variation_id = $item->get_variation_id();
   $product = $item->get_product();
   $name = $item->get_name();
   $quantity = $item->get_quantity();
   $subtotal = $item->get_subtotal();
   $total = $item->get_total();
   $tax = $item->get_subtotal_tax();
   $taxclass = $item->get_tax_class();
   $taxstat = $item->get_tax_status();
   $allMeta = $item->get_Meta_data();
   $someMeta = $item->get_Meta( '_whatever',true );
   $type = $item->get_type();
}

税率不是其中的一部分。所以我想我需要第二个数组?

解决方法

要获取订单商品的税级,请查看此处:

然后您可以创建一个自定义函数,该函数根据指定的税种对订单商品的总数求和

该函数有两个参数

  • $order_id:要从中获取总计的订单的 ID
  • $tax_class:用作过滤器的税种(默认设置为“reduced-rate”)

所以:

// gets the total of the order items by tax class
function get_total_order_items_by_tax_class( $order_id,$tax_class = 'reduced-rate' ) {
    $order = wc_get_order( $order_id );
    // initializes the total of the order items
    $total = 0;
    foreach( $order->get_items() as $item_id => $order_item ) {
        // if the product tax class is equal to "$tax_class"
        if ( $tax_class == $order_item['tax_class'] ) {
            // sum the total
            $total += $order_item['total'];
        }
    }
    return $total;
}

用法

如果您想根据 {{1} } tax class 你可以这样做:

60

如果您想根据 reduced-rate 税种过滤产品,您可以使用:

$total = get_total_order_items_by_tax_class( 60 );

因为 standard 税类 slug 是空的。

代码已经过测试并且可以正常工作。