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

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.

| improve this answer | |
  • 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 Oct 7 '14 at 14:30
  • 1
    @alex I mean avoiding relying on globals to pass information around – Rarst Oct 7 '14 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 Oct 7 '14 at 15:22
  • Oh and then you access the variables as $this->var? Clever ... – giraff Aug 21 '15 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.

| improve this answer | |
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/

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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