修改WooCommerce商品小计仅生效于购物车,求全局生效解决方案
解决WooCommerce商品小计仅在购物车页生效的问题
你当前的代码仅通过woocommerce_cart_subtotal钩子修改小计,但这个钩子只作用于购物车页面。要让结账页、订单邮件等全局场景都生效,需要针对不同场景使用对应的钩子,并确保核心计算逻辑在各个场景中复用。
原代码问题分析
你使用的woocommerce_cart_subtotal钩子作用范围有限,结账流程和订单邮件会直接调用购物车/订单的原始计算值,不会触发这个钩子,导致各页面小计不一致。
解决方案
通过封装核心计算逻辑+多钩子覆盖的方式,实现全局场景的小计统一:
// 封装核心小计计算逻辑,所有场景复用 function custom_calculate_cart_subtotal() { global $pur_mode; $custom_subtotal = 0; if ( ! WC()->cart ) return $custom_subtotal; foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $listt = $cart_item['list-cart-type']; $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key ); if ( $_product && $_product->exists() && $listt == $pur_mode && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) { $custom_subtotal += $cart_item['line_total']; } } return $custom_subtotal; } // 覆盖购物车页面小计显示 add_filter( 'woocommerce_cart_subtotal', 'custom_override_cart_subtotal', 99, 3 ); function custom_override_cart_subtotal( $cart_subtotal, $compound, $cart ) { $custom_subtotal = custom_calculate_cart_subtotal(); return wc_price( $custom_subtotal ); } // 覆盖结账页面订单小计计算 add_filter( 'woocommerce_calculated_total', 'custom_override_checkout_subtotal', 99, 2 ); function custom_override_checkout_subtotal( $total, $cart ) { return custom_calculate_cart_subtotal(); } // 订单创建时同步自定义小计,确保邮件、订单详情页一致 add_action( 'woocommerce_checkout_create_order', 'custom_set_order_subtotal', 99 ); function custom_set_order_subtotal( $order ) { $custom_subtotal = custom_calculate_cart_subtotal(); $order->set_subtotal( $custom_subtotal ); // 同步更新订单总额(按需调整,若包含运费、税费等需对应计算) $order->set_total( $custom_subtotal + $order->get_shipping_total() + $order->get_tax_total() - $order->get_discount_total() ); }
代码说明
custom_calculate_cart_subtotal():提取你原有的筛选计算逻辑,作为统一的计算规则,避免重复代码woocommerce_cart_subtotal:保持购物车页面的小计格式化显示woocommerce_calculated_total:修改结账流程中的订单总额计算逻辑woocommerce_checkout_create_order:在订单生成时写入自定义小计,确保后续订单详情、邮件通知都使用统一值
内容的提问来源于stack exchange,提问作者joel alemaida
相关产品推荐
相关产品推荐

