如何在 Timber 中通过 ACF 字段动态构建 WordPress 查询

6次阅读

如何在 Timber 中通过 ACF 字段动态构建 WordPress 查询

本文讲解如何在 timber 模板上下文($context)中正确获取 acf 自定义字段值,并将其作为变量用于 `timber::get_posts()` 查询,避免因作用域或数据未加载导致的空值问题。

在 Timber + ACF 开发中,直接调用 get_field(‘cat_name’)(如原代码所示)往往无法按预期工作——因为该函数默认作用于当前全局 $post,而 home.php 作为首页模板通常不处于具体文章上下文中,且 Timber 的 $context[‘post’] 尚未被正确初始化为 TimberPost 实例时,get_field() 可能返回 false 或空值。

✅ 正确做法是:先确保 $context[‘post’] 是一个有效的 TimberPost 对象,再通过其 get_field() 方法安全读取 ACF 字段。TimberPost::get_field() 内部已封装 ACF 兼容逻辑,会自动处理字段类型、子字段、关联对象等,是 Timber 推荐的标准访问方式。

以下是修正后的 home.php 完整示例:

get_field('cat_name');  // ✅ 可选:添加空值校验,提升健壮性 if (empty($cat_name)) {     $cat_name = 'uncategorized'; // 默认回退分类 }  // 构建查询参数:按分类别名(category_name)筛选文章 $context['posts'] = Timber::get_posts([     'post_type'      => 'post',     'category_name'  => $cat_name,     'posts_per_page' => 6,     'post_status'    => 'publish' ]);  Timber::render('home.twig', $context); ?>

? 注意事项与最佳实践:

  • ⚠️ get_field(‘cat_name’) 在首页模板中不可靠,因其依赖 WordPress 全局 $post,而首页通常无此上下文;务必改用 $timber_post->get_field()。
  • ? 若 cat_name 存储的是分类 ID 而非别名,请改用 ‘cat’ => (int) $cat_name 参数,并确保字段返回数值。
  • ? 如需支持多分类或自定义分类法,建议使用 tax_query 替代 category_name,例如:
    'tax_query' => [     [         'taxonomy' => 'category',         'field'    => 'slug',         'terms'    => $cat_name     ] ]
  • ? 在 Twig 模板中,可直接输出该变量调试:{{ post.get_field(‘cat_name’) }} 或 {{ cat_name }}(若已赋值到 context)。

通过以上方式,你不仅能安全获取 ACF 字段值,还能将其无缝集成进 Timber 查询逻辑,实现基于 cms 配置的动态内容展示。

text=ZqhQzanResources