You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce:如何在价格与短描述间加文本并修复结账页异常

解决WooCommerce产品页添加3%折扣价文本并修复结账页混乱问题

问题根源

你之前的代码未限制执行场景,导致结账等非产品详情页也触发了钩子逻辑,进而出现页面混乱或代码显示的问题。只需给代码加上页面判断,同时通过内联样式设置文本为绿色即可解决。

方案1:在价格后、短描述前添加文本

替换主题functions.php里的旧代码为以下内容:

add_action( 'woocommerce_single_product_summary', 'show_3percent_off_price', 15 );
function show_3percent_off_price() {
    // 仅在单个产品详情页执行,避免干扰其他页面
    if ( ! is_product() ) return;

    global $product;
    $regular_price = $product->get_regular_price();
    $discounted_price = $regular_price * 0.97;
    $formatted_price = wc_price( $discounted_price );

    // 输出绿色样式的折扣文本
    echo '<p style="color: #2ecc71; margin: 10px 0;">立减3%专享价:' . $formatted_price . '</p>';
}

代码说明

  • 钩子woocommerce_single_product_summary的优先级15,刚好卡在价格(优先级10)和短描述(优先级20)之间
  • is_product()确保代码只在产品详情页运行
  • color: #2ecc71是清新绿色,可替换为green、#008000等你需要的色值
  • wc_price()自动适配店铺的货币格式设置

方案2:将文本添加到短描述首行

如果需要把折扣文本放在短描述开头,用这段代码替换:

add_filter( 'woocommerce_short_description', 'prepend_discount_to_short_desc', 10, 1 );
function prepend_discount_to_short_desc( $short_desc ) {
    if ( ! is_product() || empty( $short_desc ) ) return $short_desc;

    global $product;
    $regular_price = $product->get_regular_price();
    $discounted_price = $regular_price * 0.97;
    $formatted_price = wc_price( $discounted_price );

    $discount_text = '<p style="color: #2ecc71; font-weight: bold;">立减3%专享价:' . $formatted_price . '</p>';
    return $discount_text . $short_desc;
}

注意事项

  • 修改functions.php前务必备份文件,防止出错导致网站异常
  • 优先使用子主题的functions.php添加代码,避免主题更新时代码丢失

内容的提问来源于stack exchange,提问作者user21183243

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:10:14