The get_template_part() function in
WordPress is used to call a part of a template in a theme file. The third argument allows you to pass variables to the template. This section explains how to use it and how to check it appropriately.
Basic usage of get_template_part()
The normal usage of get_template_part()
is as follows
get_template_part( 'template-parts/content', 'single' );
The above code calls template-parts/content-single.php
from within the theme. At this time, there are no parameters to pass to the template.
Passing Variables to Templates Using the Third Argument
The third argument can be used to pass data to the template. For example, you can pass a variable as follows
get_template_part( 'template-parts/content', 'single', array( 'custom_param' => 'value' ) );
In this case, you can refer to the value passed as $args
in the template file.
How to check $args
When using $args
in a template, it is important to check that the variable is set. This is done using the isset() function
.
The above code outputs the value of $args['custom_param']
only if it is set.
Summary
Using the third argument of get_template_part()
, it is possible to pass data to the template in a flexible manner. Use the isset() function
to verify that the data is set correctly and to properly manage your templates.