Passing variables when loading templates in WordPress

One caveat faced by developers using get_template_part is the inability of passing variables to the loaded templates. There is, however an alternative using locate_template.

Overview

In this example we’re going to display three Easy Digital Download entries. I’ve been using EDD for a while now and while it has a lot of features it’s still surprisingly lightweight. We’ll be fetching the entries and saving them in the variable $edd_download. We will then load the template passing the variable. Actually, to pass the variable is to say too much. We’ll be simply loading the template in a way the $edd_download variable has the proper scope to be used in the template loaded.

Caller code

This code can be placed in a function. You can then plug that function to an area of your theme using an action hook or simply call the function as a template tag. In my themes, I use hooks so users can later add or remove content. This is all we need for the code:

[php]
‘download’,
‘posts_per_page’ => 3,
)
);

if ( $edd_download ) {
// Check if the template exists and save its location
$part = locate_template( ‘parts/download-home.php’ );
if ( ” != $part ) {
// if the template location was returned, load it
require $part;
}
}
[/php]

Template code

Now we need the template file. If you notice the call above, the locate_template expects to find the file download-home.php in the directory parts inside the theme folder.

[php]

<a class="product-link" href="” title=””>


[/php]

We must always remember to call wp_reset_postdata() after a foreach loop if we called setup_postdata().

Closing Words

So after all this, why is this useful? because users can create a template in a child theme and easily override the original template. It’s all about making life easier for your users. Sure, this can also be achieved through filters or creating pluggable functions but some users might consider editing a template focused on one task a cleaner approach than dealing with a file with a lot of functions for several different and unrelated tasks.

4 thoughts on “Passing variables when loading templates in WordPress”

Leave a Reply to Chinmay Dixit Cancel reply