我正在尝试使用 Timber (Twig) 从另一个页面访问 ACF 数据以显示在另一个页面上。
ACF 在“关于”页面中的名称是 the_unstrung_hero
(id = 7)。
page-home.php:
<?php
$context = Timber::get_context();
$post = new TimberPost();
$about_page_id = 7;
$about = new TimberPost($about_page_id);
$about->acf = get_field_objects($about->ID);
$context['post'] = $post;
Timber::render( array( 'page-' . $post->post_name . '.twig', 'page.twig' ), $context );
在 page-home.twig 中:
<p>{{ acf.the_unstrung_hero|print_r }}</p>
这只是许多组合的最后一次尝试。坦率地说,我只是没有得到什么(PHP 不是我的强项)...非常感谢您的帮助。
最佳答案
在上面的示例中,我看到您从“关于”页面获取字段数据,但并未将其添加到上下文中。您的模板不会显示该数据,因为您没有将其交给模板。
首先设置上下文:
$context = Timber::get_context();
然后得到当前应该显示的post数据:
$post = new TimberPost();
现在你确实加载了 $post
,但它还不在你的上下文中。您必须将要在页面上显示的数据放入 $context
数组中。然后通过 Timber::render( 'template.twig', $context )
渲染它。您的 Twig 模板将仅包含存在于 $context
中的数据(为了完整起见:您还可以使用 Twig 模板中的函数来获取数据,但这是另一个主题)。
要同时添加您从“关于”页面加载的数据,您必须这样做:
$about_page_id = 7;
$about = new TimberPost( $about_page_id );
$context['about'] = $about;
看到行 $about->acf = get_field_objects($about->ID)
不存在了吗?您不需要它,因为 Timber 会自动将您的 ACF 字段加载到发布数据中。现在可以通过 Twig 模板中的 {{ about.the_unstrung_hero }}
访问您的字段。
回到你想要实现的目标:
我会这样解决。
赞Deepak jha mentionend 在你的问题的评论中,我还会使用 get_field()
函数的第二个参数通过帖子 ID 从帖子中获取字段数据。
如果您只想显示一个 ACF 字段的值,您实际上不需要加载关于页面的整个帖子。
page-home.php
$context = Timber::get_context();
$post = new TimberPost();
$context['post'] = $post;
// Add ACF field data to context
$about_page_id = 7;
$context['the_unstrung_hero'] = get_field( 'the_unstrung_hero', $about_page_id );
Timber::render( array( 'page-' . $post->post_name . '.twig', 'page.twig' ), $context );
然后在 page-home.twig 中,您可以在帖子中访问字段数据。
<p>{{ the_unstrung_hero }}</p>
关于php - 木材:从另一个页面访问高级自定义字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36704448/