如何在WordPress的Timber中使用Custom Post Type并遍历ACF重复字段
嘿,我太懂你这种卡在ACF Repeater字段遍历的感觉了!我之前用Timber配合ACF做自定义文章类型的时候也踩过一模一样的坑,给你一步步捋清楚正确的做法:
第一步:确保Functions.php里的上下文传递正确
首先你得保证自定义文章类型的数据已经正确传给Timber的上下文,其实Timber对ACF的支持很友好,不需要手动去调用get_field()(当然也可以),默认通过post.meta()就能拿到所有ACF字段。这里给你一个标准的Functions.php示例:
function load_custom_cpt_template($templates) { // 替换成你的自定义文章类型slug if (is_singular('your_cpt_slug')) { $context = Timber::context(); $context['post'] = Timber::get_post(); // 如果你想手动把repeater字段单独提出来也可以,不过其实不需要 // $context['my_repeater'] = get_field('your_repeater_field_name', $context['post']->ID); Timber::render('single-your-cpt-slug.twig', $context); return []; // 告诉WordPress我们已经处理了模板渲染 } return $templates; } add_filter('template_include', 'load_custom_cpt_template');
第二步:在Twig模板里正确遍历Repeater字段
假设你的ACF Repeater字段名叫project_features,里面的子字段是feature_title(文本)、feature_description(文本框),还有feature_icon(图片字段,设置为返回“图片对象”),那Twig里的写法应该是这样:
{% if post.meta('project_features') %} <div class="project-features"> <h2>项目特性</h2> {% for feature in post.meta('project_features') %} <div class="feature-item"> <!-- 处理图片字段 --> {% if feature.feature_icon %} <img src="{{ feature.feature_icon.src }}" alt="{{ feature.feature_icon.alt }}" class="feature-icon"> {% endif %} <h3>{{ feature.feature_title }}</h3> <p>{{ feature.feature_description }}</p> </div> {% endfor %} </div> {% else %} <p>暂无项目特性信息</p> {% endif %}
几个容易踩的坑要注意:
- 字段名要完全匹配:ACF里的字段名是小写下划线格式(比如
project_features),Twig里写错一个字符都拿不到数据 - 确保字段组关联到你的CPT:去ACF的字段组设置里检查“位置”规则,是不是选了你的自定义文章类型
- 图片字段的返回格式:如果ACF图片字段设置的是“URL”,那直接用
{{ feature.feature_icon }}就行;如果是“图片对象”,Timber会自动转成Timber\Image实例,这时候可以用src、alt、甚至resize()这类Timber的图片处理方法
内容的提问来源于stack exchange,提问作者robertguss
相关产品推荐
相关产品推荐

