首页 > 解决方案 > WooCommerce:仅从降低税率的商品中获取订单总额

问题描述

我只想从降低税率的项目中导出总计。

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

我现在想要项目 A 和 B 的总和。在这种情况下,总价值为 157,50 欧元。

我找到了一个代码片段来获取类的总税额:

// 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变量中使用任何东西。

我想我需要检查订单的所有项目。但是我怎么能按税率选择这些项目呢?

我在这里找到了一些东西:

// 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();
}

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

标签: phpwordpresswoocommerceorderstax

解决方案


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

然后,您可以创建一个自定义函数,根据指定的税种对订单项目的总数进行求和

该函数有两个参数

  • $order_id:您要从中获取总计的订单的 ID
  • $tax_class:用作过滤器的税类(默认设置为“降低税率”)

所以:

// 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;
}

用法

如果您想根据税类获取具有订单ID 的订单项目的总和,您可以执行以下操作:60reduced-rate

$total = get_total_order_items_by_tax_class( 60 );

如果您想根据standard税级过滤产品,您可以使用:

$total = get_total_order_items_by_tax_class( 60, '' );

因为standard税类 slug 是空的。

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


推荐阅读