WordPress get_template_part pass variable

Using WordPress 5.5+

As of WordPress 5.5, passing variables via get_template_part is part of core.

Starting in WordPress 5.5, the template loading functions will now allow additional arguments to be passed through to the matched template file using a new $args parameter.

get_template_part( string $slug, string $name = null, array $args = null  )

Example:

<?php 
get_template_part( 'template-parts/featured-image', null, array( 
  'class' => 'featured-home',
  'data'  => array(
    'size' => 'large',
    'is-active' => true,
  )) 
);
?>

and then in the included file (i.e. template-parts/featured-image), you can either just display the variables (as per above example) :

if ( $args['class'] ) {
  echo $args['class'];
}

or

echo $args['data']['size'];

alternatively setup defaults first, using wp_parse_args:

// Setup defaults
$array_defaults = array( 
  'class' => 'featured',
  'data' => array(
    'size' => 'medium',
    'is-active' => false,
   )
); 

$args = wp_parse_args( $args, $array_defaults );


<div class="widget <?php echo esc_html( $args['class'] ); ?>">
    <?php echo esc_html( $args['data']['size'] ); ?>
</div>

To be backwards compatible in your theme, you should probably also check the current WordPress version.

Using set_query_vars

The original answer to this questions was to use set_query_var

In your theme:

<?php
set_query_var( 'my_var_name', 'my_var_value' );
get_template_part( 'template-parts/contact' );
?>

In the template part:

<?php
$newValue = get_query_var( 'my_var_name' );
if ( $newValue ) {
  // do something
}
?>

Leave a Comment