Reputation: 621
Please bear with me because I am new to this. So I have a custom field that I created using Advanced Custom fields in Wordpress.
The name of my template code is template-test.php
and contains the following
<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>
Now, when I use Wordpress admin to preview page template-test.php
by clicking the update button and clicking preview. I can see my posts (the contents of 'sponsor_advertisement_one' and 'sponsor_advertisement_two')
But when I try to include the same template file into another page (home.php) using:
<?php include("template-test.php"); ?>
only the text within the span shows up.
Note: both php pages (template-test.php and home.php are in the same directory.
I've been banging my head against the wall on this.
Upvotes: 0
Views: 1424
Reputation: 2286
If you look at the ACF docs, get_field() accepts a $post_id as the 2nd argument, which defaults to the current post if it's not provided.
So, if you include that file in your template-test page, the template-test page ID will be passed (and will work), but if you include it on our home page, the home page ID is passed, which won't work since that page doesn't have any content in those fields.
If you want to get access to those fields in any page ID context, it needs to be provided explicitly, and it should work regardless of where it's included. If you know the page slug, you could get the ID by using that.
$page = get_page_by_path('my-slug');
get_field('sponsor_advertisement_one', $page->ID);
get_field('sponsor_advertisement_two', $page->ID);
ACF get_field() docs: https://www.advancedcustomfields.com/resources/get_field/
Upvotes: 1