WooCommerce修改购物车与结账页小计:将10%押金价转为全额总价
WooCommerce购物车/结账页显示全额总价(替代10%押金)
以下两种方法可实现需求,优先推荐钩子函数方案(避免模板更新冲突),也可直接修改子主题模板文件:
方法一:修改子主题cart-totals.php文件(小计乘10)
- 打开子主题目录下的
cart-totals.php,找到显示「小计」的代码块(通常是类似下面的结构):
<tr class="cart-subtotal"> <th><?php esc_html_e( 'Subtotal', 'woocommerce' ); ?></th> <td data-title="<?php esc_attr_e( 'Subtotal', 'woocommerce' ); ?>"><?php wc_cart_totals_subtotal_html(); ?></td> </tr>
- 替换为以下代码,将当前10%押金的小计乘以10得到全额总价,并修改标签文字:
<tr class="cart-subtotal"> <th><?php esc_html_e( '全额总价', 'woocommerce' ); ?></th> <td data-title="<?php esc_attr_e( '全额总价', 'woocommerce' ); ?>"> <?php // 获取当前显示的押金小计 $deposit_subtotal = WC()->cart->get_subtotal(); // 计算全额总价 $full_total = $deposit_subtotal * 10; // 按WooCommerce规则格式化价格输出 echo wc_price( $full_total ); ?> </td> </tr>
- 保存文件后刷新购物车/结账页即可生效。
方法二:通过钩子函数实现(更稳定,推荐)
直接修改模板文件可能在WooCommerce版本更新后失效,使用钩子函数更可靠,步骤如下:
- 打开子主题的
functions.php文件,添加以下代码:
// 替换购物车/结账页的小计为全额总价(基于押金乘10) add_filter( 'woocommerce_cart_subtotal', 'replace_deposit_with_full_amount', 10, 3 ); function replace_deposit_with_full_amount( $subtotal_html, $compound, $cart ) { $full_total = $cart->get_subtotal() * 10; return wc_price( $full_total ); } // 修改小计标签为「全额总价」 add_filter( 'woocommerce_cart_totals_subtotal_label', 'update_subtotal_label_to_full' ); function update_subtotal_label_to_full() { return esc_html__( '全额总价', 'woocommerce' ); }
如果需要通过累加每个商品的原价计算全额(适配不同商品押金比例的场景),替换上面的钩子函数为:
// 累加商品原价计算全额总价 add_filter( 'woocommerce_cart_subtotal', 'calculate_full_total_from_items', 10, 3 ); function calculate_full_total_from_items( $subtotal_html, $compound, $cart ) { $full_total = 0; // 遍历购物车所有商品 foreach ( $cart->get_cart() as $item ) { // 获取商品原价(可根据实际需求切换为get_sale_price()) $product_price = $item['data']->get_regular_price(); // 累加单价×数量 $full_total += $product_price * $item['quantity']; } return wc_price( $full_total ); }
- 保存文件后刷新页面即可看到效果。
注意事项
- 测试时确认押金插件是否修改了购物车小计的计算逻辑,若方法一失效,优先使用钩子方案。
- 若仅需在特定页面(如仅购物车页)修改,可在函数中加入页面判断:
if ( is_cart() ) { ... }。 - 修改
functions.php前建议备份文件,避免语法错误导致网站异常。
内容的提问来源于stack exchange,提问作者Marco Bagiacchi
相关产品推荐
相关产品推荐

