The get_template_part() function is tremendously useful for breaking up your templates into discrete components. You can even use get_template_part() within The WordPress Loop, and all of the usual Loop variables and functions – like the_content() and the_title() – can be accessed from within your template part, no extra effort required.

The Problem

But what if you need to pass some other kind of variable into your template part? One that isn’t part of the standard set of global variables that are accessible from any template?

// Parent Template (or Template Part)
$myvar = 'hey!';
get_template_part( 'component' );
// component.php Template Part
echo $myvar;
// This value is undefined

As you can see, $myvar isn’t accessible to the component.php template part.

The Solution

Use the set_query_var() and get_query_var() functions. Your variable can hitch a free ride alongside the standard WP_Query object that is passed down into descendant template parts. Here’s how it’s done:

Use the set_query_var() function in the parent template, like so:

// Parent Template (or Template Part)
$myvar = 'hey!';
set_query_var( 'myvar', $myvar );
get_template_part( 'component' );

Then use get_query_var() in your template part, like this:

// component.php Template Part
$myvar = get_query_var( 'myvar', default );
echo $myvar;
// Outputs "hey!"

Photo by Marc-Antoine Dépelteau on Unsplash