Wordpress - Passing variables through locate_template
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()
A neat solution found in the codex
So if you are looping thru custom posts, you can do this:
foreach ($custom_posts as $custom_post) {
set_query_var( 'my_post', $custom_post );
get_template_part( 'content', 'part' );
}
And in that template itself, you will automatically get a $my_post
.
I've had trouble with this too (while trying to get a custom query to work with a template part). The short answer is: no, the template part doesn't automatically inherit custom vars the way a regular include does.
Both get_template_part() and locate_template() eventually use the load_template() function to actually load the file (using a require). This function globalizes the following vars:
$posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID
However, no other vars appear to be available from inside the template part. I guess since the actual require is wrapped in a function, the scope changes or something?
Anyhoo, I'd try globalizing any additional vars you need to pass, then calling up those globals from your template part.