While I’ve typically used include
or require
on their own to save long term code maintenance I’ve started to use get_template_part
and locate_template
as using built in WordPress stuff is always best.
My question is are you supposed to be able to pass variables through to the results of either get_template_part
or locate_template
?
<?php
$var = get_option( 'my-custom-option' );
get_template_part( 'custom-template-part' );
?>
In the code above the $var
would be printed inside the custom template but the variable doesn’t seem to work. Am I missing something or is this expected behaviour?
I’ve found that they don’t pass in the instance above or when using locate_template
<?php
locate_template( 'custom-template-part.php', true );
?>
Like MathSmath wrote, get_template() does not support the re-use of your variables.
But locate_template() infact does no inclusion at all. It just locates a file for inclusion.
So you can make use of include to have this working just like you expect it:
include(locate_template('custom-template-part.php'));
$var
from your example can be used in the template part then.
A related question with a more technical explanation of the variable scope and get_template(): Form Submitting Error with get_template_part()