2

I am developing a custom theme and i like to pass some variables to selected files. I am calling the view files from functions.php.

$var1 = ;
$var2 = ;
etc
include_once('form-views/view-profile.php');//works

//get_template_part('includes/form-views/view','profile');//doesn't work

Now with include it works

3 Answers 3

1

This is essentially scope visibility issue. include brings code into a current scope, function call creates new closed off scope. In get_template_part() only certain WordPress globals are being made available by load_template() call inside.

While the basic answer is to declare your variables as globals, you might want to ponder your overall architecture a bit — this is typically not a good sign in code.

4
  • do you mean i should avoid using include? I thought i was doing a better architecture by using a view and have a function deciding which view to load.
    – alex
    Commented Oct 7, 2014 at 14:30
  • 1
    @alex I mean avoiding relying on globals to pass information around
    – Rarst
    Commented Oct 7, 2014 at 15:04
  • i don't use globals with the include version. At the moment i am trying github.com/Smartik89/SMK-Theme-View/blob/master/functions.php which looks ok. It wraps the load_template function in another function. But it adds more code?
    – alex
    Commented Oct 7, 2014 at 15:22
  • Oh and then you access the variables as $this->var? Clever ...
    – giraff
    Commented Aug 21, 2015 at 12:39
1

In these cases, I usually use:

include(locate_template('includes/form-views/view-profile'));

In this way, a child theme can override the file.

0

WordPress 5.5 allows passing $args to get_template_part. Apart from this function there are sets of template function which can now accept arguments.

get_header
get_footer
get_sidebar
get_template_part_{$slug}
get_template_part

Please refer more details at: https://make.wordpress.org/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/

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.