【问题标题】:Timber: Access Advanced Custom Field From Another Page木材:从另一个页面访问高级自定义字段
【发布时间】:2016-04-18 21:17:51
【问题描述】:

我正在尝试使用 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 不是我的强项)...您的帮助将不胜感激。

【问题讨论】:

  • 您是否尝试过使用 acf 字段 id 而不是名称“the_unstrung_hero”?
  • 如何获取 ACF 字段“ID”?谢谢
  • 在添加/编辑 ACF 字段(字段组)时,单击“屏幕选项”,您将看到一个复选框“字段键”。检查并且您将能够在字段左侧看到“字段键”(或我使用的 ID)。
  • 我尝试过字段键 - 让我感到困惑,因为你说的是​​“字段 id”。
  • 你可以试试这个the_field('the_unstrung_hero',7);

标签: php wordpress twig timber


【解决方案1】:

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

您首先设置上下文:

$context = Timber::get_context();

然后你得到当前应该显示的帖子数据:

$post = new TimberPost();

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

要添加您从 about 页面加载的数据,您必须这样做:

$about_page_id = 7;
$about = new TimberPost( $about_page_id );
$context['about'] = $about;

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

回到你想要达到的目标:

我会这样解决的。

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

如果您只想显示一个 ACF 字段的值,则不需要加载 about 页面的整个帖子。

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 中可以访问 post 中的字段数据。

<p>{{ the_unstrung_hero }}</p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-31
    • 2015-05-27
    • 2016-06-28
    • 2021-02-18
    • 2016-01-20
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    相关资源
    最近更新 更多