0
votes

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.

1
If you are calling it in a different location try using get_template_part('template','test'); instead of include. I think you are using ACF plugin make sure you put the post ID. It is missing the specific post ID where your value was entered. - Maqk
roots.io/routing-wp-requests explains the wordpress page life cycle. Basically a page template displays data provided to it by the wordpress 'routing' system (you can have multiple pages use the same template, and each will show different content), so including it somewhere else isnt going to do much. - Steve
@Maqk Thanks for the explanation - Mariton

1 Answers

1
votes

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/