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
// This is the var we'll use 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 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
/**
 * Created by elio.blog
 * 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(); ?>
    </a>
</article>

<?php endforeach; 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.

Advertisements

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

Leave a Reply