Passing variables to get_template_part() in WordPress

This morning I needed to pass a variable to a file that I was including using the WordPress get_template_part function.

I was fiddling around with global variables when I thought there must be a better way. There is.

Locate and include

You can use the WordPress locate_template function within PHP’s include(). It’s done like this:

[code]include(locate_template(‘your-template-name.php’));[/code]

All of the variables available in your current script will be available in that template file now too.

55 responses to “Passing variables to get_template_part() in WordPress”

  1. Zeally Avatar

    Thank you very much. This solution also works for child theme.

  2. Nick Avatar

    Killer — this works wonders. Thank you. Saved me a ton of queries.

  3. X Avatar

    Wow thanks for this! It works like magic 🙂

  4. hannahc Avatar

    locate_template(‘my/template.php’, true, true) also works – the last two parameters concern loading and requiring. The second parameter specifies whether to load the template, and the third parameter determines whether to use ‘require’ or ‘require_once’ – false for the first, true for the latter.

  5. hannahc Avatar

    Or not, actually – seems I was wrong. WordPress really needs to add this behaviour in by default!

  6. Robbiegod Avatar

    hey, this solved my problem. Specifically i was trying to use a $count++; variable in a get_template_part portion of my page and well the variable would not increment. Switching to your include -> locate_template worked like a charm. Thanks much!

  7. Technoh Avatar

    Note that if you use the second parameter of locate_template it will prevent variables from being passed to the loaded template, presumably because it is loaded in a sandbox. Simply use require(locate_template(‘template.php’)) instead.

  8. Richard Avatar

    Tidy solution! This works great for custom admin screens

  9. Tino Avatar

    You’re a life saver. This works like a treat!

  10. simongcc Avatar

    Thanks for your inspiration!

    reference: http://codex.wordpress.org/Function_Reference/locate_template

    Actually digging into the source, the following is same:

    include(locate_template(‘content-profile.php’)); //because default is not load
    it return a path of the file, so the following is working the same

    using this is working-> locate_template(‘content-profile.php’, true); //true means load the file

  11. simongcc Avatar

    Hi I think I was wrong for previous post, I was missed, the load_template put “require_once” inside a function, it cannot read anything other than global declared inside.

    Sorry for convenience caused. Thanks for posting.

  12. simongcc Avatar

    I think I was wrong in previous comment

    locate_template(‘content-profile.php’, true); //true means load the file
    => not working to pass the variable since

    The process of locate_template() is:
    locate_template() called load_template() and
    load_template() called require_once() or require() with global variable settings inside the function

    So variable outside global scope does not pass it because the require_once is being called inside a closed function load_template()

    so Keith’s method is the best solution to take it
    for anyone need the advantage of locate_template(), may use Keith’s method 🙂
    include, include_once, require, require_once are working for it

  13. Andres Avatar

    I was pulling my hair out for an hour before I found this post. Thanks!

  14. Linkin Avatar

    Thank you for this post. Very helpful.
    Will appreciate some advice in the following scenario.

    I am looping an array and passing the current array value to another php file as follows:

    foreach( $pieces as $piece ) {
    include(locate_template( array( ‘helper_file.php’ ), true, false ))
    /* true = load if found
    /* false = load on every iteration */
    }

    In helper_file.php I have
    global $piece; var_dump($piece);

    without Keith’s method var_dump print NULL
    Keith’s method works but var_dump gets printed twice. 🙁
    I want it to print only once.

    Please advice some alternative.

  15. Roman Avatar

    Thanks Keith!
    I was expecting to have access to the variables when loading template part… and was wondering what’s happening. Your code have solved me some frustration today!!

  16. zgreen Avatar

    Indeed, very helpful.

    As other commentators have noted, using

    locate_template(‘your-template-name.php’, true, true);

    will not load any variables from your-template-name.php.

    You must use include(locate_template(‘your-template-name.php’));

  17. AJ Clarke Avatar

    Very useful, thanks 😉

  18. thanks Avatar

    You saved my life!!! Thanks!!!

  19. clarkandyh Avatar

    After trying a million different combinations this allowed me to access variables in the include file. Thanks, but why isn’t this better documented?

  20. Sylvain Avatar

    Thanks a lot.
    This is very helpful.

  21. Stijn de Witt Avatar

    I am using this variation for BuddyPress:

    include( bp_locate_template( array( ‘my/template.php’ ) ) );

    BuddyPress expands upon WordPress’s locate_template by adding in some extra fallbacks. Specifically, to look in ‘buddypress’ subfolder of plugins’ / themes’ template directories. This allows BuddyPress plugin devs to hook into the resolving.

    For the rest it seems to work similarly. Thanks for your post. If you are in the mood for editing it, I would matbe explicitly mention the fact that

    locate_template( array( ‘my/template.php’ ), true /* load */ );

    is NOT equivalent to writing out the include manually. The local variables from the calling script are NOT available in the located template this way.

    It saves people from digging through the comments 🙂

  22. Laszlo Avatar

    Thank you very much. It was very helpful for me.

  23. Petruza Avatar

    Great tip, thanks!

  24. […] uses under the hood and run a quick include(locate_template('your-template-name.php'));, as Keith Devin explains. Happy […]

  25. calete Avatar

    awesome, simple and functional

  26. David Avatar

    Thank you very much for this solution!

  27. Bivek Avatar

    this worked for me.. Thanks a lot…

  28. Tibor Avatar

    Thanks a million! I was struggling miles to pass a variable into a template part that was loaded through an ajax request…this solution made me dance around the room 🙂

  29. Jepser Avatar

    So much thanks keith!

  30. Nedvajz Avatar

    Function below uses Keith’s way and improve it a bit to use easily and controll what pass to template you including. (Btw thanks Keith for your method a lot!!!)

    Use like:

    element(‘template-part’, array(
    ‘variable’ => ‘whatever’,
    ‘variable2’ => array(1,2,3)
    ))

    /**
    * element
    *
    * @param mixed $template
    * @param mixed $data
    * @access public
    * @return template
    */
    function element($template, $data) {
    ob_start();
    extract($data);
    include(locate_template(sprintf(‘%s.php’, $template)));
    return ob_get_clean();
    }

  31. Mattias Avatar

    Great stuff! Just what I needed. Thanks!

  32. […] This method also means you’ll be creating some de facto templates to display specific FCF types accordingly so you might consider loading them into your loop via include(locate_template()). […]

  33. kamiel Avatar

    Thanks! This works nicely. It really slims down my theme as I don’t need to include different templates for posts that just change by one CSS class (that I don’t want to set with javascript). Thumbs up!

  34. Bayyu Idham Avatar

    Works like a charm !! Thanks..

  35. […] found this solution, I thought i’d expand on that solution and create a function to replace the […]

  36. vivian Avatar

    my file is

    in above case want to pass variable $i inside xyz.
    so can i use yours method inside loop?

  37. Rachel Avatar

    This saved my life right here! Small, but powerful tip! Thanks.

  38. Arman Avatar

    You have no idea how much time you just saved me. Thanks!

  39. Herus Avatar

    // You wish to make $my_var available to the template part at `content-part.php`
    set_query_var( ‘my_var’, $my_var );
    get_template_part( ‘content’, ‘part’ );

    1. Philipp Avatar

      This is really the way to do it properly.
      Don’t use `include()`!

      To get the variable, use get_query_var().

  40. D.Lo Avatar

    This is the greatest solution ever. So simple. Previously I had to do funky things with global variables and functions to replicate the functionality, but it never felt right or elegant. This is perfect. THANK YOU!!!

  41. Patrick Avatar

    Thanks Keith, good tip.

  42. Russy Avatar

    Or you can use global variables

    1. manu Avatar

      Thank you. I think this is a better solution that the one provided by this article.

  43. calvin Avatar

    Good call worth looking at the extra arguments in my initial rush I saw my content added twice ! as I was using it with the load and then including it as well. So working for me is..include(locate_template(‘template-parts/tray.php’,false)); if false isn’t set then it does the include twice and crucially the first time the var isn’t available.

  44. ONLYPS Avatar

    just user
    in templte file $r = “hi”;

    in template part:
    global $r;
    echo $r;
    it will work fine

  45. Maxime CULEA Avatar

    Hi,
    In my company we have managed to handle this with a custom class : https://github.com/BeAPI/bea-template-vars
    Working like a charm !

  46. […] course! One alternative is to use something like the following, as pointed out by Keith Devon, instead of […]

  47. Christos Avatar

    You may easily pass variables to a template part, using the set_query_var / get_query_var functions, which are wrapper functions for the identically named WP_Query class methods.

    SET THE VARIABLES:

    $options = array( ‘option1’ => ‘value1’, ‘option2’ => ‘value2’ );
    set_query_var( ‘my_options’, $options );
    get_template_part( ‘templates/example/part’ );

    RETRIEVE THE VARIABLES IN TEMPLATE PART

    $options = get_query_var( ‘my_options’ );
    if ( is_array( $options ) ) { extract($options); }
    echo ‘This is my option 1 value: ‘. $option1 .”;
    echo ‘This is my option 2 value: ‘. $option2;

    …and just my two cents for theme authors. I think that the locate_template function suggested in this article is not the expected choice to include a template part. You might get the same result using it, nevertheless it does not provide the extra do_action trigger that get_template_part does…and some plugins might rely on it. In addition, using an include() function for your template parts will produce several alert notices on several quality review tools ( such as the Theme Check plugin ).

  48. Rob Avatar

    Why not just include the file in the first place rather than using get_template_part() ?

    That way it’s aware of the variables from file that includes it.

    Not WordPress standard practice (but then you are still using include in the template part anyway) but seems a lot more sensible than loading a template part and then loading the file that included it again. Infinitely loading files within themselves could lead to a lot of issues. At least consider using include_once instead of include.

Leave a Reply

Your email address will not be published.