在 WooCommerce 项目中,产品价格显示通常受主题和插件共同影响。如果希望统一修改前端价格样式或补充营销信息,最稳妥的方式是利用系统提供的过滤器,并结合自定义短代码在任意位置调用商品数据。

为什么需要优化价格显示
默认情况下,WooCommerce 会在商品列表与详情页输出固定格式的价格。当业务上需要展示省了多少钱、会员专享价等文案时,直接修改模板文件会带来维护负担。使用过滤器可以减少耦合。
常用价格相关钩子
woocommerce_get_price_html:改写商品最终 HTML 价格串woocommerce_format_sale_price:控制促销价排版
通过过滤器优化价格显示
下面的示例在原价后追加一条折扣提示,仅对处于促销状态的商品生效。
// 在主题 functions.php 中添加
add_filter('woocommerce_get_price_html', 'my_custom_price_html', 10, 2);
function my_custom_price_html($price, $product) {
if ($product->is_on_sale()) {
$regular = (float) $product->get_regular_price();
$current = (float) $product->get_sale_price();
if ($regular > 0) {
$off = round(($regular - $current) / $regular * 100);
$price .= ' <span class="discount-tip">立省' . $off . '%</span>';
}
}
return $price;
}
自定义短代码集成价格调用
如果编辑想在普通文章里展示某个商品的实时价格,可以注册一个短代码,通过商品 ID 获取信息。
短代码函数写法
// 注册 [product_price id="123"] 短代码
add_shortcode('product_price', 'my_product_price_shortcode');
function my_product_price_shortcode($atts) {
$atts = shortcode_atts(array('id' => 0), $atts, 'product_price');
$product = wc_get_product(intval($atts['id']));
if (!$product) {
return '商品不存在';
}
// 直接调用系统方法,保持与商城一致
return $product->get_price_html();
}
在文章中使用
切换到编辑器文本模式,写入 [product_price id="56"] 即可输出对应商品的价格 HTML。由于使用了系统原生方法,显示样式和过滤器改动都会自动生效。
注意事项
| 问题 | 处理建议 |
|---|---|
| 改完不生效 | 清理站点缓存与商品缓存,确认过滤器优先级 |
| 短代码报错 | 检查 WooCommerce 是否激活,ID 是否为数字 |
提示:不要在前台用 echo 直接输出价格,统一走 get_price_html() 能减少样式错位。
通过上述方式,你可以在不修改核心文件的前提下,灵活控制 WooCommerce 价格展示,并用短代码把价格能力开放给内容编辑。
WooCommerce产品价格显示自定义短代码修改时间:2026-07-26 01:21:20