在 PHP 包含中使用时不显示自定义字段
Custom fields not displaying when used within an PHP Include
请耐心等待,因为我是新手。
所以我有一个使用 Wordpress 中的高级自定义字段创建的自定义字段。
我的模板代码名称是template-test.php
,包含以下内容
<div class="item-one"><?php the_content(); ?><span>text1</span></div>
<div class="item-two"><?php echo get_field('sponsor_advertisement_one'); ?><span>text2</span></div>
<div class="item-three"><?php echo get_field('sponsor_advertisement_two'); ?><span>text3</span></div>
现在,当我使用 Wordpress 管理员通过单击更新按钮和预览来预览页面时 template-test.php
。我可以看到我的帖子('sponsor_advertisement_one'和'sponsor_advertisement_two'的内容)
但是当我尝试使用以下方法将相同的模板文件包含到另一个页面 (home.php) 时:
<?php include("template-test.php"); ?>
仅显示范围内的文本。
注意:php 页面(模板-test.php 和 home.php 在同一目录中。
我一直在用头撞墙。
如果您查看 ACF 文档,get_field() 接受 $post_id 作为第二个参数,如果未提供则默认为当前 post。
因此,如果您将该文件包含在您的模板测试页面中,模板测试页面 ID 将被传递(并且有效),但如果您将它包含在我们的主页中,则主页 ID 将被传递,这将不起作用,因为该页面在这些字段中没有任何内容。
如果您想在任何页面 ID 上下文中访问这些字段,则需要明确提供它,并且无论它包含在何处都应该有效。如果您知道页面 slug,则可以使用它来获取 ID。
$page = get_page_by_path('my-slug');
get_field('sponsor_advertisement_one', $page->ID);
get_field('sponsor_advertisement_two', $page->ID);
ACF get_field() 文档:
https://www.advancedcustomfields.com/resources/get_field/
请耐心等待,因为我是新手。 所以我有一个使用 Wordpress 中的高级自定义字段创建的自定义字段。
我的模板代码名称是template-test.php
,包含以下内容
<div class="item-one"><?php the_content(); ?><span>text1</span></div>
<div class="item-two"><?php echo get_field('sponsor_advertisement_one'); ?><span>text2</span></div>
<div class="item-three"><?php echo get_field('sponsor_advertisement_two'); ?><span>text3</span></div>
现在,当我使用 Wordpress 管理员通过单击更新按钮和预览来预览页面时 template-test.php
。我可以看到我的帖子('sponsor_advertisement_one'和'sponsor_advertisement_two'的内容)
但是当我尝试使用以下方法将相同的模板文件包含到另一个页面 (home.php) 时:
<?php include("template-test.php"); ?>
仅显示范围内的文本。
注意:php 页面(模板-test.php 和 home.php 在同一目录中。
我一直在用头撞墙。
如果您查看 ACF 文档,get_field() 接受 $post_id 作为第二个参数,如果未提供则默认为当前 post。
因此,如果您将该文件包含在您的模板测试页面中,模板测试页面 ID 将被传递(并且有效),但如果您将它包含在我们的主页中,则主页 ID 将被传递,这将不起作用,因为该页面在这些字段中没有任何内容。
如果您想在任何页面 ID 上下文中访问这些字段,则需要明确提供它,并且无论它包含在何处都应该有效。如果您知道页面 slug,则可以使用它来获取 ID。
$page = get_page_by_path('my-slug');
get_field('sponsor_advertisement_one', $page->ID);
get_field('sponsor_advertisement_two', $page->ID);
ACF get_field() 文档: https://www.advancedcustomfields.com/resources/get_field/