php - WooCommerce:仅从降低税率的商品中获取订单总额
问题描述
我只想从降低税率的项目中导出总计。
例如,我有 2 件商品的税率降低,一件商品的税率正常:
- A 项: 100€ - 5,00€ 减税 - 105,00€ 总计
- B 项: 50€ - 2,50€ 减税 - 52,50€ 总计
- C 项:100€ - 19,00€ 正常税 - 119,00€ 总计
我现在想要项目 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();
}
但税率不是其中的一部分。所以我想我需要第二个数组?
解决方案
要获取订单商品的税级,请查看此处:
然后,您可以创建一个自定义函数,根据指定的税种对订单项目的总数进行求和。
该函数有两个参数:
$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 的订单项目的总和,您可以执行以下操作:60
reduced-rate
$total = get_total_order_items_by_tax_class( 60 );
如果您想根据standard
税级过滤产品,您可以使用:
$total = get_total_order_items_by_tax_class( 60, '' );
因为standard
税类 slug 是空的。
该代码已经过测试并且可以工作。
推荐阅读
- ios - 四舍五入货币值(SwiftUI、Core Data)
- reactjs - 从 Webview 获取和传递 React Native 中的变量
- spring-boot - 反向 tls 代理后面的 Primefaces 主题不适用
- python - 从两个基础镜像(centos 和 python)构建一个新的 docker 镜像
- c# - 将内容和编译文件从 nuget 复制到 .net 核心项目中
- shell - VB6 - 当我单击命令按钮时如何执行存储在字符串变量中的文件
- node.js - nodejs中函数外的json变量的范围是什么?
- reactjs - TS2339 Typescript 错误,但不确定为什么...类型上不存在属性
- java - Java swing.How to override component methods in intellij idea GUI desinger
- git - 让 Git Bisect 进行强制签出或以其他方式覆盖本地更改