Why does get_template_part() break variables?

In PHP, when you include a file, the variables you’re using in your current scope are available for use in the included file.

When using WordPress’s get_template_part(), variables are no longer available in the “included” file.

get_template_part() calls locate_template() which then calls load_template(), which then performs the require or require_once.

If WordPress eventually calls PHP’s require, why do the variables no longer work? Is it something to do with the 3 function calls before the actual require?

1 Answer
1

A script loaded within a function call will only work within the immediate scope of where require or include was used. So really only variables present when load_template() is called will be accessible to the loaded script (unless you use global $myvar of course).

The reason vars like $post and $wp_query are available to the script is because load_template() globals them in before loading the script.

If you wanted to make sure your script can access certain vars, either global them in or add them to the $wp_query->query_vars array before loading (not recommended but depending on the task it might be the only feasible option), as those get extracted into the local scope before loading the script.

Leave a Comment