Updated: November 1, 2017
This is a Knowledge Base post.
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: https://codex.wordpress.org/Function_Reference/get_template_part
EDIT: According to http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/ you can also use this:
include(locate_template('your-template-name.php'));