WordPress: Passing Params to get_template_part()

Last updated on July 13, 2021 A Goodman Loading... Post a comment

When using the get_template_part function in WordPress, you can pass parameters to it as shown below:

<?php 
get_template_part( 'my-templates/aweasome-post-template', null, [
    'value1' => 'ABC',
    'value2' => 'Kindacode.com',
    'value3' => 'DEF'
  ]
);
?>

Then you can retrieve the passed variables in the template file like this:

<?php
// my-templates/aweasome-post-template.php 
if ( $args['value1'] ) {
  echo $args['value1'];
}

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

if ( $args['value3'] ) {
  echo $args['value3'];
}
?>

In this case, $args is a reserved word.

Make sure you use one of the most recent versions of WordPress (5.5+ or newer). Happy coding!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like