When developing s WordPress Theme, one of the most frequently used features is the get_template_part() function. It allows us to include templates in another template. It is really helpful in segregation of code and makes management of complex projects quite simple. I was kind of over-confident of the usage of this function that I had stopped referring to the Codex for this function. Recently, I happened to bump into this function’s page in the Codex and was surprised to see that there was an additional parameter… the $args parameter, which allows transmitting any data to the template being called. For any theme developer, this is an amazing feature and solves a lot of problems.
Why use this
While developing a WordPress theme, one of the major points to consider is providing multiple blog layout. Some prefer multiple columns, while others want to add additional classes based on some customizer control. Earlier, including different templates based on Customizer Controls was a complex task requiring conditional statements and a lot of different files. With the adevent of this parameters, the code will get shorter and there will be lesser number of files.
How does it work
The $args parameter accepts an array. We can pass as many values we want to this array and they all will be available in the template through the $args variable. Consider the following code-
get_template_part('template-parts/content','blog', array( 'key1' => 'value1', 'key2' => 'value2' ));
We call content-blog.php in the template-parts folder and pass an array containing key value pair to the third parameter. This parameter will be available in the content-blog.php template as a $args variable.
$args = array( 'key1' => 'value1', 'key2' => 'value2' );
We can use it as we please. The value of this parameter can be controlled using the customizer, dashboard, external plugin or however we wish to control it. This flexibility allows us to control the template.
Hope you liked this little snippet of WordPress. For more of such tips, tricks and tutorials, head on to our blog. We publish articles on a regular basis.