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

如何让Advanced Custom Field的before_price字段显示在WooCommerce价格前

方案1:调整现有钩子优先级

你现在的代码显示在价格后面,是因为WooCommerce默认将商品价格挂载到woocommerce_single_product_summary钩子的优先级为10,你设置的优先级和价格一致,执行顺序就排在了价格之后。把优先级改为小于10的数值(比如9)即可,修改后的代码如下:

/**
 * Display before_price custom field on frontend before product price
 * @since 1.0.0
 */
add_action( 'woocommerce_single_product_summary', 'shoptimizer_before_price', 9 );
function shoptimizer_before_price() { 
    if(get_field('before_price')) { ?>
        <div class="cg-before_price"><?php the_field('before_price'); ?></div>
    <?php }
}

如果需要让前缀和价格显示在同一行,你可以在主题自定义CSS里添加以下样式:

.cg-before_price {
    display: inline-block;
    margin-right: 6px;
}

方案2:直接过滤价格HTML(更稳妥,不受主题钩子顺序影响)

如果你担心后续主题调整钩子顺序导致位置偏移,可以直接通过价格过滤钩子把自定义字段内容插入到价格HTML最前面,代码如下:

/**
 * Add before_price custom field before product price HTML
 * @since 1.0.0
 */
add_filter( 'woocommerce_get_price_html', 'add_before_price_prefix', 10, 2 );
function add_before_price_prefix( $price, $product ) {
    $prefix = get_field('before_price', $product->get_id());
    if( $prefix ) {
        $price = '<span class="cg-before_price">' . esc_html($prefix) . '</span> ' . $price;
    }
    return $price;
}

这个方案的优势是不管是商品详情页还是商品列表页的价格,都会自动加上前缀,不需要额外添加其他钩子。

内容的提问来源于stack exchange,提问作者Subscription Box Australia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:42:00