2

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?

5
  • Possible duplicate of wordpress.stackexchange.com/questions/4462/… Commented Feb 23, 2016 at 20:04
  • @czerspalace That seems like a "How to" and this sounds like a "Why does" type question.
    – Howdy_McGee
    Commented Feb 23, 2016 at 20:12
  • @Howdy_McGee got it. Should I delete my comment? Commented Feb 23, 2016 at 20:37
  • @czerspalace Nah, the community could agree and close the question as dup. I just thought the two were different in principle.
    – Howdy_McGee
    Commented Feb 23, 2016 at 20:39
  • 1
    Files included inside a function get the scope of that function. That'll probably get flagged as low quality if I post it as an answer!
    – Milo
    Commented Feb 23, 2016 at 21:25

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.