修改WooCommerce购物车与结账汇总:字段增删及计算需求
解决WooCommerce购物车/结账页总计字段修改问题
以下是通过PHP钩子实现需求的具体方案,无需修改核心文件,直接添加到主题的functions.php文件或自定义插件中:
核心代码实现
// 自定义购物车与结账页的总计字段 add_filter( 'woocommerce_get_order_item_totals', 'custom_cart_checkout_totals', 10, 3 ); function custom_cart_checkout_totals( $total_rows, $order, $tax_display ) { // -------------------------- // 1. 移除指定字段(根据实际键名调整) // -------------------------- // 示例:移除"小计"和"折扣"字段,键名可通过var_dump($total_rows)查看确认 unset( $total_rows['cart_subtotal'] ); unset( $total_rows['discount'] ); // -------------------------- // 2. 添加"商品总价"字段(所有产品原价之和,不含折扣) // -------------------------- // 区分购物车状态和已下单状态的数值获取 $product_subtotal = WC()->cart ? WC()->cart->get_subtotal() : $order->get_subtotal(); $total_rows['product_subtotal'] = array( 'label' => __('商品总价', 'woocommerce'), 'value' => wc_price( $product_subtotal ), ); // -------------------------- // 3. 替换"最终总价"字段(商品总价 - 折扣金额) // -------------------------- $discount_total = WC()->cart ? WC()->cart->get_discount_total() : $order->get_discount_total(); $final_total = $product_subtotal - $discount_total; // 替换原有"订单总价"为"最终总价" $total_rows['order_total']['label'] = __('最终总价', 'woocommerce'); $total_rows['order_total']['value'] = wc_price( $final_total ); // -------------------------- // 可选:调整字段显示顺序(将最终总价放在最后) // -------------------------- $final_total_row = $total_rows['order_total']; unset( $total_rows['order_total'] ); $total_rows['order_total'] = $final_total_row; return $total_rows; }
关键说明
- 字段键名确认:如果代码移除的字段不对,可在函数开头添加
var_dump($total_rows); exit;,刷新购物车页查看所有字段的键名,替换unset中的对应键即可。 - 数值计算逻辑:
- 商品总价:调用
get_subtotal()获取所有商品原价总和(不含折扣、税费) - 最终总价:商品总价减去折扣总金额,确保计算逻辑符合需求
- 商品总价:调用
- 兼容性:该代码兼容WooCommerce 3.0+版本,无需修改核心文件,避免升级丢失修改。
内容的提问来源于stack exchange,提问作者Marco Bagiacchi
相关产品推荐
相关产品推荐

