Passing arguments to get_template_part

Using the built-in WordPress function to encourage reusable components

December 2020

Since WordPress 5.5.0 it has been possible to pass arguments/data to the Get template part function. This was a much requested feature, and is great for reusing components throughout a site.

To reuse a component, call it in your template file. This example assumes a component named 'reusable-component.php' is in a 'template-parts' folder in your theme. The third argument is where we pass data to the component as an array:

<?php get_template_part('template-parts', 'reusable-component', ['foo' => 'bar']); ?>

In the component, the 'foo' variable can then be accessed inside the $args array:

<?php // Prints 'bar' to the page`
echo $args['foo']; ?>

Want to hire me for a project, or to fix something on your website? Get in touch 😀

stevencotterill.com © 2020