木材:从另一个页面访问高级自定义字段

3 php wordpress twig timber

我正在尝试从另一个页面访问 ACF 数据,以便使用 Timber (Twig) 在另一个页面上显示。

ACF 名称the_unstrung_hero位于“关于”页面(id = 7)中。

页面-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 );
Run Code Online (Sandbox Code Playgroud)

在 page-home.twig 中:

<p>{{ acf.the_unstrung_hero|print_r }}</p>
Run Code Online (Sandbox Code Playgroud)

这只是许多人的最后一次组合尝试。坦率地说,我只是没有得到一些东西(PHP 不是我的强项)...您的帮助将不胜感激。

Gch*_*htr 5

在上面的示例中,我看到您从 about 页面获取字段数据,但没有将其添加到上下文中。您的模板不会显示该数据,因为您没有将其交给模板。

您首先设置您的上下文:

$context = Timber::get_context();
Run Code Online (Sandbox Code Playgroud)

然后您将获得应显示的当前帖子数据:

$post = new TimberPost();
Run Code Online (Sandbox Code Playgroud)

现在你确实 load $post,但它不在你的上下文中。您必须将要在页面上显示的数据放入$context数组中。然后你渲染它Timber::render( 'template.twig', $context )。您的 Twig 模板将仅包含存在于中的数据$context(要完整:您还可以使用 Twig 模板中的函数来获取数据,但这是另一个主题)。

要添加从关于页面加载的数据,您必须执行以下操作:

$about_page_id = 7;
$about = new TimberPost( $about_page_id );
$context['about'] = $about;
Run Code Online (Sandbox Code Playgroud)

看到这条线$about->acf = get_field_objects($about->ID)不再存在了吗?您不需要它,因为 Timber 会自动将您的 ACF 字段加载到帖子数据中。现在可以通过{{ about.the_unstrung_hero }}Twig 模板访问您的字段。

回到你想要达到的目标:

我会像这样解决它。

就像在您的问题的评论中提到的Deepak jha一样,我还将使用该get_field()函数的第二个参数通过帖子 ID 从帖子中获取字段数据。

如果您只想显示一个 ACF 字段的值,您实际上不需要加载关于页面的整个帖子。

主页-home.php

$context = Timber::get_context();
Run Code Online (Sandbox Code Playgroud)

然后在page-home.twig 中,您可以访问 post 中的字段数据。

<p>{{ the_unstrung_hero }}</p>
Run Code Online (Sandbox Code Playgroud)