You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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>';
} ?>

关键细节解释

  1. 筛选商品行项目:用$order->get_items('line_item')仅获取商品类订单项,避免处理运费、优惠券等非商品项导致的错误。
  2. 安全判断订单项类型:通过instanceof WC_Order_Item_Product确保当前项是商品订单项,防止调用非商品方法报错。
  3. 从订单项取编辑后价格:$item->get_price()直接返回后台编辑后的该商品行单价,是订单专属的修改后价格,与产品全局价格无关。
  4. 价格格式化与安全输出:
    • wc_price()自动处理货币符号、小数位数,适配商店的货币设置。
    • esc_html()转义商品名称和数量,避免XSS安全风险。
  5. 兼容产品不存在场景:判断$product是否存在,避免因商品已删除或为虚拟商品时调用产品方法触发报错。

内容的提问来源于stack exchange,提问作者MattHamer5

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 03:05:20