Passing variables to a WordPress template efficiently

One challenge faced by theme or plugin developers using get_template_part is the inability to pass variables to the loaded WordPress template. 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’ll then load the WordPress 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.

Loading a WordPress template

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:

 '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;
    }
}

Template code

Now we need the WordPress 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.


    

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 to a WordPress template efficiently”

Leave a Reply