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

WooCommerce按页面及促销状态为价格添加前缀的实现问题

问题描述

我参考Stack Overflow的《Add a custom text before the price display in WooCommerce》回答,想要实现以下需求:

  • 仅促销商品显示指定文本,非促销商品要么显示其他文本要么不显示价格前缀
  • 商品页的关联产品区域不显示该文本,只在单个商品的主区域展示
  • 不同页面(单商品页、商店页、归档页、搜索列表等)显示不同的价格前缀文本

但我用了下面的代码,没达到预期效果:

add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );
function cw_change_product_price_display( $price ) { 
    if ( is_product() && $product->is_on_sale() ){ 
    // Your additional text in a translatable string 
        $text = __('TEXT'); // returning the text before the price return 
        $text. ' ' . $price; 
    } 
    return $price; 
}

问题分析

原代码存在几个关键问题:

  1. 没获取当前商品对象$product,直接调用$product->is_on_sale()会报错
  2. 仅判断了单商品页,未区分其他页面类型
  3. 没有处理关联产品区域的排除逻辑
  4. 代码里的文本拼接没有赋值回变量,最后还是返回原价格
  5. 未处理非促销商品的文本规则

修正后的代码

add_filter( 'woocommerce_get_price_html', 'custom_price_prefix_based_on_product_and_page', 10, 2 );
function custom_price_prefix_based_on_product_and_page( $price, $product ) {
    // 排除商品页的关联产品区域
    if ( is_product() && ! empty( $GLOBALS['woocommerce_loop']['name'] ) && $GLOBALS['woocommerce_loop']['name'] === 'related' ) {
        return $price;
    }

    // 根据页面和促销状态设置前缀文本
    if ( $product->is_on_sale() ) {
        // 促销商品:分页面设置不同文本
        if ( is_product() ) {
            $prefix = __( '限时特惠:', 'text-domain' );
        } elseif ( is_shop() || is_product_category() || is_product_tag() ) {
            $prefix = __( '特惠价:', 'text-domain' );
        } elseif ( is_search() ) {
            $prefix = __( '搜索特惠:', 'text-domain' );
        } else {
            $prefix = __( '促销价:', 'text-domain' );
        }
        $price = $prefix . ' ' . $price;
    } else {
        // 非促销商品:需要前缀就取消下面两行注释,不需要就留空
        // $prefix = __( '日常售价:', 'text-domain' );
        // $price = $prefix . ' ' . $price;
    }

    return $price;
}

代码说明

  • 获取产品对象:钩子woocommerce_get_price_html自带$product参数,直接使用即可
  • 排除关联产品:通过全局变量判断当前是否是关联产品循环,是的话直接返回原价格
  • 分页面适配:用is_product()、is_shop()等条件函数区分页面,给促销商品设置不同前缀
  • 促销/非促销区分:通过$product->is_on_sale()判断商品状态,非促销商品的前缀可按需开启
  • 翻译支持:用__()函数包裹文本,替换text-domain为你的主题/插件域名,方便多语言适配

注意事项

  • 不需要添加woocommerce_cart_item_price钩子(需求未提及购物车价格前缀)
  • 确保商品已正确设置促销价(填写了销售价格字段)
  • 测试时可以清空缓存,避免旧代码生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 21:12:17