ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-27 05:31:07  阅读:269  来源: 互联网

标签:twig wordpress-plugin timber wordpress php


我试图使用Timber(Twig)从另一个页面访问ACF数据以在另一个页面上显示.

ACF名称在“关于”页面(id = 7)中为the_unstrung_hero.

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 = 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提及一样,我也将使用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>

标签:twig,wordpress-plugin,timber,wordpress,php
来源: https://codeday.me/bug/20191027/1942006.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有