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:

include(locate_template('your-template-name.php'));

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

WordPress SEO: 10 tips for better search rankings

FREE E-book. Learn the basics of WordPress SEO and how to improve the key metrics
  • We won't sell your address to anyone. We hate spam too.
View my portfolio Get in touch

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

  1. hannahc

    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.

    Reply
  2. hannahc

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

    Reply
  3. Robbiegod

    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!

    Reply
  4. Technoh

    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.

    Reply
  5. simongcc

    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.

    Reply
  6. simongcc

    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

    Reply
  7. Linkin

    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.

    Reply
  8. Roman

    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!!

    Reply
  9. zgreen

    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’));

    Reply
  10. clarkandyh

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

    Reply
  11. Stijn de Witt

    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 🙂

    Reply
  12. Tibor

    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 🙂

    Reply
  13. Nedvajz

    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();
    }

    Reply
  14. kamiel

    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!

    Reply
  15. vivian

    my file is

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

    Reply
  16. Herus

    // 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’ );

    Reply
    • Philipp

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

      To get the variable, use get_query_var().

      Reply
  17. D.Lo

    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!!!

    Reply
    • manu

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

      Reply
  18. calvin

    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.

    Reply
  19. Christos

    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 ).

    Reply
  20. Rob

    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.

    Reply

Leave a Reply to Bivek

Click here to cancel reply.