WordPress: Passing variables to get_template_part

I had an issue with a project that needed a simple way to carry variables over to small templates which would make life much easier.

I found this solution, I thought i’d expand on that solution and create a function to replace the get_template_part() issue.

The key to this function is php’s extract() function, so by simply sending a variable containing an array of variables you can then pass that data to your template files within the new function.

/**
 * Load a template part into a template
 *
 * Makes it easy for a theme to reuse sections of code in a easy to overload way
 * for child themes.
 *
 * Includes the named template part for a theme or if a name is specified then a
 * specialised part will be included. If the theme contains no {slug}.php file
 * then no template will be included.
 *
 * The template is included using require, not require_once, so you may include the
 * same template part multiple times.
 *
 * For the $name parameter, if the file is called "{slug}-special.php" then specify
 * "special".
 * 
 * For the var parameter, simple create an array of variables you want to access in the template
 * and then access them e.g. 
 * 
 * array("var1=>"Something","var2"=>"Another One","var3"=>"heres a third";
 * 
 * becomes
 * 
 * $var1, $var2, $var3 within the template file.
 *
 * @since 3.0.0
 *
 * @param string $slug The slug name for the generic template.
 * @param string $name The name of the specialised template.
 * @param array $vars The list of variables to carry over to the template
 * @author Eugene Agyeman zmastaa.com
 */
function get_template_part2( $slug, $name = null,$vars=null ) {
	/**
	 * Fires before the specified template part file is loaded.
	 *
	 * The dynamic portion of the hook name, `$slug`, refers to the slug name
	 * for the generic template part.
	 *
	 * @since 3.0.0
	 *
	 * @param string $slug The slug name for the generic template.
	 * @param string $name The name of the specialized template.
	 * @param array $vars The list of variables to carry over to the template
	 */
	do_action( "get_template_part_{$slug}", $slug, $name );

	$templates = array();
	$name = (string) $name;
	if ( '' !== $name )
		$templates[] = "{$slug}-{$name}.php";

	$templates[] = "{$slug}.php";

	extract($vars);
	foreach ($templates as $template){
		include(locate_template($template));
	}
}

 

Using this function you can now call templates like this

 

$variables_to_be_created = array(
		"var1"=>"something",
		"var2"=>11111,
		"array_var"=>array("data"=>"nested array")	
);
get_template_part2($slug,null,$variables_to_be_created);

 

In your template file the new variables will now be accessible as $var1, $var2, $array_var

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *