passing variables to get_template part in wordpress

When including part of a theme using the wordpress function get_template_part(), you will notice the included template will not have access to any variables previously defined, this is because they are now out of scope.

For example the template foo.php will not have access to $a:

$a =1;
get_template_part('foo');

There are two main work a rounds:

1. Global Technique

$a=1;
get_template_part('foo');

in foo.php

global $a;

By adding Global $a; into the template foo.php will allow the template to access the variable $a

2. Locate and include

$a=1;
include(locate_template('foo.php'));

By using locate_template to generate a path and php’s include it is possible to include the template as though it was a block of code in line with the existing code thus consequently has access to the current scope.

Both of which I am not keen on, the global fix (1) downside is that you will need to declare global on each and every variable you wish to use, and the use of global is bad.
The second, Locate and include (2) downside is that should the template not exist a warning will be displayed, this is because a check before hand is not being performed, this leads to more code to check for the files existence or suppress the error, furthermore the code included has the potential to modify any variables in the existing scope.

My approach is to use an extra function added to the themes functions.php file

$a=1;
get_partial('foo',array('a'=>$a)); 

The function behaves in the same way as get_template_part() but performs all the correct checks before hand thus stopping any errors, then assigns the variables to the scope, includes the template, and finally returns a success of true or false.

The function to add is below (simply copy and paste into functions.php)

function get_partial($template, array $args = array()){
    $template   = locate_template(preg_replace("/(.+)\.php$/", "$1", $template).'.php'); 
    if (file_exists($template)){
        global $posts, $post, $wp_did_header, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID;
        extract($args);
        include($template);
        return true;
    }
}

Happy coding!

VN:F [1.9.9_1125]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.9_1125]
Rating: +1 (from 1 vote)
passing variables to get_template part in wordpress, 10.0 out of 10 based on 1 rating

2,298 views

This entry was posted on Thursday, July 23rd, 2015 at 10:08 am and is filed under Wordpress. You can follow any responses to this entry through the RSS 2.0 feed.

Leave a Reply