The post data are not actually passed to the template part. There is a global variable called $post
which contains data about the current post, such as post’s ID.
When you call a template part by using get_template_part()
, the WordPress will look inside that template and run whatever is inside it, outputting it in the loop.
For example, if you use the_title()
inside your template part, WordPress will try and run the_title()
function, which depends on the post ID. However, since the global $post
variable is available inside your template part, the call to $post->ID
will be successful, and the_title()
function will successfully print out the title of the current post.
If you want to pass some data to your template part, you can use set_query_var();
instead. Consider a loop like this:
if (have_posts()) {
while(have_posts()) {
the_post();
set_query_var( 'sample', 'sample_value' );
get_template_part("template/part", "example");
}
}
This will pass the sample to the template file, which can be retrieved by using this line of code :
extract( $wp_query->query_vars );
and then printed by:
var_dump( $sample);
I hope now you have some deeper understanding about how this feature works.