Passing variables to a template part in WordPress

I recently included a template part called preview-post.php within a WordPress loop using:

get_template_part( 'modules/preview' 'post' )

This worked perfectly however I then wanted to access the $count variable that I had attached to my WordPress loop within that template. This did not work as the template part could not access the variables from the file it was being included in.

After consulting the WordPress codex I found that it was possible by using this:

// You wish to make $count available to the template part at `preview-post.php`
set_query_var( 'count', $count );
get_template_part( 'modules/preview', 'post' );

More details can be found here:

EDIT: According to you can also use this:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s