Shoora
4/22/2019 - 9:41 AM

[Passing variables to template-parts] Pass PHP variables to WordPress partials as query_vars. #php #wordpress

[Passing variables to template-parts] Pass PHP variables to WordPress partials as query_vars. #php #wordpress

Passing variables to template-parts

In passing variables to get_template_part() in wordpress, the author suggests bypassing WordPress's built-in mechanism, but a commenter provides the correction solution:

/**
* 1. Set the variables
*/
$options = array(
'option1' => 'value1',
'option2' => 'value2'
);

set_query_var( 'my_options', $options );

/**
* 2. Include the template part
*/
get_template_part( 'template-parts/page/content', 'page' );

/**
* 3. Retrieve the variables in the template part
*/
$options = get_query_var( 'my_options' );

if ( is_array( $options ) ) {

/**
* predeclare the expected variables
* @see http://kb.dotherightthing.dan/php/wordpress/extract/
*/
$option1 = null;
$option2 = null;

/**
* only overwrite the predeclared variables
* @see http://kb.dotherightthing.dan/php/wordpress/extract/
*/
extract($options, EXTR_IF_EXISTS);
}

echo $option1;
echo $option2;