You need to enable JavaScript to run this app. 如何在WooCommerce外使用Timber、Twig、ACF免额外调用获取产品价格
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce外使用Timber、Twig、ACF免额外调用获取产品价格

解决方案

有两种可行方法可以满足需求,无需在Twig循环内重复调用wc_get_product:

方案1:直接读取产品元字段

你看到的_regular_price、_sale_price、_price都是WooCommerce存储在post_meta表的原生字段,ACF返回的产品对象本质是WP_Post实例,直接通过get_post_meta即可获取对应值,Twig写法如下:

{% for product in post.get_field('showcase_products') %}
    {# 第三个参数为true表示返回单条文本值 #}
    {% set regular_price = fn('get_post_meta', product.ID, '_regular_price', true) %}
    {% set sale_price = fn('get_post_meta', product.ID, '_sale_price', true) %}
    {% set current_price = fn('get_post_meta', product.ID, '_price', true) %}

    {# 示例输出 #}
    <div class="price-wrap">
        <span class="regular-price">¥{{ regular_price }}</span>
        {% if sale_price is not empty %}
        <span class="sale-price">¥{{ sale_price }}</span>
        {% endif %}
    </div>
{% endfor %}

注意:本方法读取的是数据库存储的静态价格值,如果你的站点有多货币切换、动态税费、会员折扣等动态价格规则,静态值会和实际生效的售价不符。


方案2:PHP层提前预处理数据(更推荐)

如果需要用到WooCommerce原生的价格计算、格式化(比如带货币符号的价格HTML),可以在往Twig传递数据的环节,提前把ACF返回的产品数组全部转成WC_Product对象,避免在模板层重复调用转换函数。示例PHP代码(以Timber框架为例):

// 获取ACF中继器返回的产品数组
$raw_products = get_field('showcase_products');
$processed_products = [];

// 遍历转换为WC_Product对象
foreach ($raw_products as $p) {
    if (is_a($p, 'WP_Post')) {
        $processed_products[] = wc_get_product($p->ID);
    }
}

// 将处理好的产品数组传入Twig上下文
$context['showcase_products'] = $processed_products;

处理完成后在Twig中可以直接调用WC原生方法,无需额外转换:

{% for product in showcase_products %}
    {# 直接输出WooCommerce格式化好的价格HTML #}
    {{ product.get_price_html() }}
    <p>当前售价:{{ product.get_price() }}</p>
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 21:36:01