Passing variables via get_template_part() in WordPress

Passing variables via get_template_part() in WordPress

Similar to native include() or require() PHP functions, WordPress introduces its own get_template_part() function to load templates (PHP files) on the website front-end (WordPress theme).

While using get_template_part is good in many cases, there are also some points where get_template_part() function makes things harder for developers. Precisely, there is not a possibility to pass PHP variables to a template which is included via get_template_part(). Let’s take a look at some basic examples and an elegant workaround.

Why using get_template_part()?

One word (actually two) – Child Themes. Yes, if you want to change some of the theme files (templates) via child theme, calling get_template_part() is a way to go.

Basically, when you call get_template_part(‘some-file’) WordPress will first check if the file with the same path and name exists in the child theme. If the file exists, it will load the file from the child theme instead of parent and this is really a neat solution to override some template which you want to change without touching the original (parent) theme files. Here is a basic example:

And here is a basic example of content.php file.

The problem with get_template_part() variables

Now, what if we have a custom variable in loop.php file which we want to use in content.php file as well. Take a look:

When we try to use $example variable in content.php it becomes unrecognized.

Usual workaround is to use global statement before defining or calling variable each time in each of the templates and that way it will be recognized. It may be ok for one variable in just one place but for many variables and complex template structure it’s not so elegant, right? We want to avoid calling global multiple times.

A workaround – using include() and locate_template()

If you dig deeper into WordPress code you will see that get_template_part() actually uses another function called locate_template() which is basically used to detect if a template exists in child theme. Optionally, locate_template() may load template (and clear all variables as get_template_part) or it may just return the path to an actual file without loading it.

Combining locate_template() and native PHP include() function, we get exactly what we need. See:

Now, when we try to use $example variable in content.php, everything is fine!

Feel free to try and let us know if this helps!

Bojan Petrovic

Co-founder and WordPress developer at Meks. He has been involved in the business since 2009. creating themes, plugins and services on top of WordPress, continuously aiming to choose best approaches and work smarter, not harder.

7 comments

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *