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

在Timber/Twig的ACF自定义块中获取Post Object/Relationship字段数据求助

解决Timber/Twig ACF自定义块中Post Object/Relationship字段无法获取数据的问题

1. 检查ACF字段返回格式

  • 打开ACF字段编辑界面,确认Post Object/Relationship字段的返回格式设置为「Post Object」而非「Post ID」。如果是ID格式,Timber无法直接识别为可操作的Post对象,需要手动转换。

2. 在统一配置中转换字段为Timber对象

如果你的自定义块通过统一PHP回调传递数据到Twig,需手动将字段转换为Timber\Post实例:

function my_acf_block_render($block, $content = '', $is_preview = false) {
    $context = Timber::context();
    $context['block'] = $block;
    $context['fields'] = get_fields();

    // 处理单个Post Object字段
    if (!empty($context['fields']['your_post_object_field'])) {
        $context['fields']['your_post_object_field'] = new Timber\Post($context['fields']['your_post_object_field']);
    }

    // 处理Relationship字段(数组形式)
    if (!empty($context['fields']['your_relationship_field'])) {
        $context['fields']['your_relationship_field'] = array_map(function($post) {
            return new Timber\Post($post);
        }, $context['fields']['your_relationship_field']);
    }

    Timber::render('path/to/your-unified-block.twig', $context);
}

3. Twig模板中正确调用字段

转换完成后,在Twig中直接调用Post对象的属性即可:

{# 单个Post Object字段调用示例 #}
{% if fields.your_post_object_field %}
    <h3>{{ fields.your_post_object_field.title }}</h3>
    <p>{{ fields.your_post_object_field.content|slice(0, 200) }}...</p>
{% endif %}

{# Relationship字段循环示例 #}
{% if fields.your_relationship_field %}
    <ul class="related-posts">
        {% for post in fields.your_relationship_field %}
            <li><a href="{{ post.link }}">{{ post.title }}</a></li>
        {% endfor %}
    </ul>
{% endif %}

4. 排查字段上下文问题

  • 在Twig模板中添加{{ dump(fields) }}(仅开发环境使用),检查Post Object/Relationship字段是否存在,以及数据类型是ID还是对象。
  • 确认统一配置中没有覆盖fields变量,导致字段数据丢失。

5. 临时禁用缓存测试

  • 禁用Timber或ACF的缓存功能,刷新页面后重新检查字段数据,避免缓存导致的旧数据问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:10:32