如何在WooCommerce中实现免运费时将迷你购物车Subtotal改为Total
解决WooCommerce迷你购物车免运费时替换“Subtotal”为“Total”的编程方法
你可以通过WooCommerce提供的过滤器钩子,结合购物车的免运费状态和税费设置,实现文本替换。下面提供两种精准的实现方式:
方法一:全局拦截文本翻译(适用于所有WooCommerce场景)
通过gettext过滤器拦截WooCommerce的文本输出,仅当满足条件时替换“Subtotal”为“Total”:
add_filter( 'gettext', 'replace_minicart_subtotal_text', 20, 3 ); function replace_minicart_subtotal_text( $translated_text, $text, $domain ) { if ( 'woocommerce' === $domain && 'Subtotal' === $text ) { global $woocommerce; $cart = $woocommerce->cart; // 满足三个条件:购物车非空 + 运费为0(免运费) + 店铺设置价格含税费 if ( ! $cart->is_empty() && $cart->shipping_total == 0 && wc_prices_include_tax() ) { $translated_text = 'Total'; } } return $translated_text; }
方法二:仅针对迷你购物车替换(更精准)
使用woocommerce_widget_shopping_cart_subtotal钩子,只修改迷你购物车的小计文本,不影响结账页等其他页面的“Subtotal”显示:
add_filter( 'woocommerce_widget_shopping_cart_subtotal', 'custom_minicart_subtotal_label', 10, 3 ); function custom_minicart_subtotal_label( $subtotal_html, $cart, $compound ) { if ( $cart->shipping_total == 0 && wc_prices_include_tax() ) { $subtotal_html = str_replace( 'Subtotal', 'Total', $subtotal_html ); } return $subtotal_html; }
使用说明
将上述任意一段代码添加到当前主题的functions.php文件中,或者使用自定义代码管理插件(如Code Snippets)来添加,避免主题更新导致代码丢失。
内容的提问来源于stack exchange,提问作者eva last
相关产品推荐
相关产品推荐

