Passing variables to WordPress get_template_part() function

How to pass a variable to get_template_part in WordPress

0 Shares
0
0
0

For this website homepage, I have created a page which will call the latest post from define category. I have created home-cat-post.php which as per my UI and requirements.

My requirement was to call same template_part file 4 times in a homepage page with different category. I was facing the issue to pass the Category Name every time I have called the template_part file.

Following solutions, I am able to find online which worked for me.

First way:

Template in which template part is included:

$value_to_sent = true;
set_query_var( 'my_var', $value_to_sent );

Included template part:

$get_my_var = get_query_var('my_var');
if ($get_my_var == true) {
...
}

Second way:

Template in which template part is included:

global $my_var;
$my_var= true;

Included template part:

global $my_var;
if ($my_var == true) {
...
}

I would rather go with the first way.

Reference Click here

I have checked on this website this is working properly