How to Pass Variables via get_template_part in WordPress

Pass variables via get_template_part or using set_query_vars

As a WordPress theme developer, sooner or later, you will encounter a situation where you need to declare a variable in one file and use it in another included one and find that you cannot directly do it. The good news is that you can pass variables via get_template_part in WordPress using two methods that we will be highlighting here.

Option 1: Passing Variables via get_template_part Using WordPress 5.5+

As of WordPress 5.5, passing variables via get_template_part is now part of the core. Previously you could only pass two parameters, slug, and name. Starting in WordPress 5.5, the template loading functions allow additional arguments to be passed through to the matched template file using a new $args parameter as the third parameter.

This is the syntax:

Here is an example of how to use the WordPress get_template_part function:

In the included template file (i.e. template-parts/geometrical-entities), you can gain access to the variables as show below:

Alternately, for cleaner code, you can setup defaults first, using wp_parse_args:

Option 2: Using set_query_vars

This option is good if you have older versions of WordPress. It is used to set the value of a query variable in the WP_Query class with the following syntax.

With this you set the variable in your theme file as follows:

In your template-part/team file you can retrieve the variable like so:

Note: The variable set by set_query_var stays in the globals. You will need to:

After the get_template_part call otherwise it will be available in the next call of the template.

In Closing

These two methods are the proper ways to variables via get_template_part in WordPress. The choice of which one to use is a matter of preference as well as the oldest version of WordPress that you intend to support as a plugin or theme developer.

Ref: [ 1 ],[ 2 ]

Read Also  How to do Binary Arithmetic by Example