Pass variables with get_template_part

Viewed 93

I have a base file called base.php, which at the top of everything has this function

  <?php if(is_page(198) || is_page(174)) : 
    $altColorClass = 'alt';
    $altColor = '#3f4549';
    
  else : 
    $altColorClass = '';
    $altColor = '#c0ccc2';
  endif 

?>

And then load a header.php

get_template_part('templates/header');

Now, in my header.php file I have the following line

<section class="header--bar <?= $altColorClass ?>">

But it doesn't get the value of altColorClass. How can I pass the variable to it when using get_template_part?

1 Answers

You should be able to pass the values using get_template_part( string $slug, string $name = null, array $args = array() ) itself. You can read more details here: get_template_part

examples from Wordpress functions:

get_template_part(
'template-part',
'name',
array(
    'key'   => 'value',
    'key2'  => 'value2'
));

In your template part

var_dump( $args );  // Everything
echo $args['key'];`  // Specific values

in your example, you can pass arguments altColorClass in the array and retrieve it in the template part, hope this helps.

Related