Skip to content

Instantly share code, notes, and snippets.

@bebaps
Created February 22, 2017 01:51
Show Gist options
  • Save bebaps/a8742b3e0d67672aa13cdca462ea2578 to your computer and use it in GitHub Desktop.
Save bebaps/a8742b3e0d67672aa13cdca462ea2578 to your computer and use it in GitHub Desktop.
Passing a variables to a template part using get_template_part()
<?php
// Set up the variable(s) to be passed as an associative array
// NOTE: it MUST be an associative array for this to work, because of the 'extract()' function to be used
$variables = [
'text' => 'See you on the other side!'
];
// Pass the array along with a reference name using the 'set_query_var()' function
// This function basically passes variables via a URL query string
set_query_var( 'passed-variables', $variables );
// Get the template part as normal
get_template_part('template-part');
<?php
// In the template part, we need to retrieve the passed variables
// Use the 'get_query_var()' function to get the passed values by their reference name
$passed = get_query_var('passed-variables');
// Now use the native PHP 'extract()' to turn the array into variables
// This should be familiar if you have ever created custom shortcodes
// Because the 'extract()' function only works with an associative array, is does not hurt to ensure that the retrieved variable is indeed an array, otherwise an error will occur
if ( is_array($passed) ) {
extract($passed);
}
// The extracted variables can now be used as normal variables
?>
<p><?php echo $text; ?></p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment