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

标签 php wordpress twig timber

我正在尝试使用 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/

相关文章:

email - 电子邮件中 Assets 的绝对路径,在 Symfony2 中没有请求对象

php - 使用单个提交按钮更新多个 SQL 记录

php - 使用 PhoneGap 发送 PHP 表单

php - 基于用户角色的 Woocommerce 最小订单总额

wordpress - 导出 WordPress 用于重定向的完整 URL 列表(网站迁移)

mysql - 如何从 WordPress 的 UserMeta 表中删除特定的 meta_key 字段及其值?

html - 如何使用 Bootstrap 在 Twig 中对齐按钮和输入

php - 如何将数组从 Symfony 2 Controller 传递到 TWIG 模板?

php - PHP 中的 SSL 帖子

javascript - 我尝试处理响应消息并打印警报,但它不起作用