
本文介绍在 WooCommerce 中通过 PHP 过滤器精准隐藏原价(stripped-through regular price),同时完整保留促销价(sale price)的 标签包裹、颜色、字体加粗等默认样式,避免因简单替换导致样式丢失。
本文介绍在 woocommerce 中通过 php 过滤器精准隐藏原价(stripped-through regular price),同时完整保留促销价(sale price)的 `` 标签包裹、颜色、字体加粗等默认样式,避免因简单替换导致样式丢失。
在 WooCommerce 默认模板中,当商品存在促销价时,woocommerce_get_price_html() 会返回类似以下结构的 HTML:
<del aria-hidden="true">¥299.00</del> <ins>¥199.00</ins>
其中 渲染为带删除线的原价, 则被 WooCommerce 样式表(如 woocommerce/assets/css/woocommerce.css)定义为绿色、加粗、无删除线——这正是我们希望保留的视觉效果。
原始代码的问题在于:wc_price($product->get_price()) 直接返回纯价格字符串(如 ¥199.00),完全绕过了 WooCommerce 内置的价格包装逻辑,导致 标签丢失,进而使促销价失去专属样式。
✅ 正确做法是复用 WooCommerce 原生的价格渲染逻辑,仅剔除 部分,而显式构造并保留 包裹的促销价。优化后的函数如下:
add_filter('woocommerce_get_price_html', 'wt_hide_regular_price', 99, 2);
function wt_hide_regular_price($price, $product) {
if (!is_cart() && !is_checkout() && !is_ajax()) {
if ($product->is_type('simple') || $product->is_type('variation')) {
return wt_regular_price_for_product($price, $product);
}
}
return $price;
}
function wt_regular_price_for_product($price, $product) {
// 仅当存在有效促销价时,才返回带 <ins> 标签的 sale price
if ($product->get_sale_price() && $product->get_sale_price() !== $product->get_regular_price()) {
$sale_price = is_numeric($product->get_sale_price())
? wc_price($product->get_sale_price())
: $product->get_sale_price();
return '<ins>' . $sale_price . '</ins>' . $product->get_price_suffix();
}
// 若无促销价,返回原价(保持默认行为)
return $price;
}</ins>
? 关键要点说明:
- 使用 标签包裹促销价,确保与 WooCommerce 默认 CSS 规则(如 .price ins { color: #78b500; font-weight: 700; })完全兼容;
- 显式调用 $product->get_price_suffix()(如“含税”或自定义后缀),维持价格完整性;
- 增加 !== $product->get_regular_price() 判断,防止价格相等时误显示 ;
- 不推荐仅用 CSS 隐藏(如 del { display: none; }),因其无法解决 缺失导致的样式降级问题,且可能影响无障碍访问(ARIA 属性丢失)。
? 提示:将以上代码添加至子主题的 functions.php 文件中,并确保已启用 WooCommerce 的价格显示功能。如需全局禁用原价(包括归档页、单产品页、搜索结果页),当前逻辑已覆盖全部非购物车/非结算场景,安全可靠。










