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.


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:

// This is the variable we'll use in the loaded template
$edd_download = get_posts( array(
    'post_type' => '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.

 * Created by 
 * This template uses $edd_download,
 * an Easy Digital Downloads entry passed as variable. 
 * @since 1.0.0 
global $post; 
foreach ( $edd_download as $post ) :
    setup_postdata( $post ); ?>
    <article class="home-product"> 
        <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'medium' ); } ?> 
            <a class="product-link" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                <?php the_title(); ?>
wp_reset_postdata(); ?>

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