Passing data to WordPress template files
The template loading functions (get_header(), get_template_part(), etc.) have a new $args argument. So now you can pass an array’s of data to the templates.
The idea is that we can now pass an object with additional, arbitrary, information for the template to use.
In this example, we load a hypothetical foo
template part and pass an array of items as the third parameter on the function call.
<?php
get_template_part(
'foo',
null,
array(
'class' => 'user',
'arbitrary_data' => array(
'foo' => 'baz',
'bar' => true,
),
)
);
We can then use this arbitrary data on the template. The example uses the class
attribute from the $args
array and from arbitrary_data
we take the foo
child element using a nested array syntax.
<div class="widget
<?php echo esc_html_class( $args['class'] ); ?>">
<?php echo esc_html(
$args['arbitrary_data']['foo']
); ?>
</div>
We can further enhance the customization using conditional tags so that only some templates use the custom variables we loaded the template with.
The functions that take the third argument are:
The affected functions are:
For more information see Passing arguments to template files in WordPress 5.5 in the Make WordPress Core blog.