Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Can you use an Array from another template part if both are used on the same page.

On my single.php I am using the

<?php get_template_part(); ?>

twice to import two different templates lets call them template 1 and template 2. On template 1 I do a loop and assign some custom fields meta data to a few variables and store everything in an array from the plugin Advanced Custom Fields and use it later on template 1.

I would also like to use that same array of data on my template 2, which it doesn't seem like it allows me to so I have to do another loop inside template 2 just to pull all the same information.

I assumed since both templates are being pulled into the same page which is single.php that I could use variables or arrays from template 1 also in template 2 without having to copy the code from template 1 to template 2. Is this correct or am I just doing something incorrectly?

1 Answer

Andrew Shook
Andrew Shook
31,709 Points

John, WordPress's get_template_part() doesn't work like PHP's native include or require function. So you can't pass variables to templates included in that manner. What you could do is create a function that generates the array and put it in your functions.php file. Then you could call the function in each template to get access to the array. Could you describe what you are putting in the array? If it's simply unaltered post information, then you shouldn't need to use an array at all, because you could access the data form the $post variable.