Posted by

Passing variables to get_template_part

This is about how to pass variables inside the file being used from get_template_parts function of wordpress. There are other ways to pass it and the common was making a variable global, which doesn’t feel right, yes?

global $test;
$test = "hello world!";
get_template_part('templates/world','hello');

Here’s the two very simple functions from wordpress you can use for this purpose. The set_query_var and get_query_var.

First is set a variable using set_query_var before the get_template_part.

set_query_var('test','hello word');
get_template_part('templates/world','hello');

Next was to use get_query_var inside the file being used by get_template_part, just open the file and insert this code.

echo get_query_var('test');

That’s it! It’s was just small thing but making your code clean feels good.