How does get_template_part() work inside a loop?

Could someone please explain to me how this function works inside a loop?

I’ve used this functions many times inside a wordpress loop like this:

loop start

  get_template_part("template/part", "example");

loop end

And the magic about this is that I can call functions like the_title() without any problem in template part-example.php.

But if I try to pass custom variables to part-example.php like this, it will fail:

$var = "variable";
Start loop

  get_template_part("template/part", "example");

End loop

And inside part-exmaple.php file

echo $var; // this will fail

I do find a workaround to solve this problem by reading great this article, it’s using include( locate_template() ).

But I just wonder, how the post data get passed through by get_template_part()?

Thanks in advance.

1 Answer
1

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.

Leave a Comment