WooCommerce订单邮件:显示编辑后折扣的商品单价
解决WooCommerce订单邮件显示编辑后商品折扣单价的问题
核心问题说明
后台编辑订单时修改的是订单项的专属价格,而非产品全局的价格,所以直接调用产品对象($product)的价格方法(如get_sale_price()、get_regular_price())要么返回产品原价,要么因产品不存在触发报错。正确的做法是从订单项对象($item)中获取编辑后的价格。
可行代码方案
<?php foreach( $order->get_items('line_item') as $item_id => $item ) { // 仅处理商品行项目,跳过运费、税费等其他类型订单项 if ( ! $item instanceof WC_Order_Item_Product ) { continue; } $name = $item->get_name(); $product = $item->get_product(); $quantity = $item->get_quantity(); // 获取订单编辑后的商品单价(未格式化) $edited_unit_price = $item->get_price(); // 获取订单编辑后的商品小计(单价×数量,未格式化) $edited_subtotal = $item->get_subtotal(); // 获取产品原价(仅当产品存在时) $regular_price = ''; if ( $product ) { $regular_price = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ); } // 格式化价格(自动适配商店货币设置) $formatted_regular_price = $regular_price ? wc_price( $regular_price ) : ''; $formatted_edited_unit_price = wc_price( $edited_unit_price ); $formatted_subtotal = wc_price( $edited_subtotal ); // 输出表格行(注意转义内容避免XSS) echo '<tr>'; echo '<td>' . esc_html( $name ) . ' × ' . esc_html( $quantity ) . '</td>'; echo '<td>' . $formatted_regular_price . '</td>'; echo '<td>' . $formatted_edited_unit_price . '</td>'; echo '<td>' . $formatted_subtotal . '</td>'; echo '</tr>'; } ?>
关键细节解释
- 筛选商品行项目:用
$order->get_items('line_item')仅获取商品类订单项,避免处理运费、优惠券等非商品项导致的错误。 - 安全判断订单项类型:通过
instanceof WC_Order_Item_Product确保当前项是商品订单项,防止调用非商品方法报错。 - 从订单项取编辑后价格:
$item->get_price()直接返回后台编辑后的该商品行单价,是订单专属的修改后价格,与产品全局价格无关。 - 价格格式化与安全输出:
wc_price()自动处理货币符号、小数位数,适配商店的货币设置。esc_html()转义商品名称和数量,避免XSS安全风险。
- 兼容产品不存在场景:判断
$product是否存在,避免因商品已删除或为虚拟商品时调用产品方法触发报错。
内容的提问来源于stack exchange,提问作者MattHamer5
相关产品推荐
相关产品推荐

