5

Is there a simple method to passing data from one file to another? I'm new to PHP and can't find a simple answer to my problem online. Apologies if this has been answered a million times & thanks in advance.

My Template 

<?php

// Declare a variable with the name of the file I want to pull in 
$critical_css = 'style';

// Header
get_header();

?>
Header 

// Get php file with inline style written inside
<?php get_template_part('/path/to/' . $critical_css); ?> 
4

The WordPress template functions don't support passing variables (to my knowledge) by default, so you need to write your own function. For example like this,

// functions.php
function my_template_include_with_variables( string $path = '', $data = null ) {
  $file = get_template_directory() . '/' . $path . '.php';
  if ( $path && file_exists( $file ) ) {
    // $data variable is now available in the other file
    include $file;
  }  
}

// in a template file
$critical_css = 'style';
// include header.php and have $critical_css available in the template file
my_template_include_with_variables('header', $critical_css);

// in header.php
var_dump($data); // should contain whatever $critical_css had

UPDATE 18.8.2020

Since WordPress 5.5 you are able to pass additional arguments with the native template functions (e.g. get_header(), get_template_part(), etc.) to the template files in an array.

From dev docs,

get_template_part( string $slug, string $name = null, array $args = array() )

| improve this answer | |
3

Simply declaring your variable as global in your header template will suffice:

<?php

global $critical_css;
get_template_part('/path/to/' . $critical_css);

?> 

No need to write your own template loading stuff (which usually is a bad idea).

| improve this answer | |
  • 1
    I think "polluting" the global space like this is considered bad practice – kero Nov 27 '19 at 12:34
  • Wouldn't 'global' need to be written in the template where the the variable is first defined? ``` global $critical_css = 'cc-frontpage'; ``` neither work unfortunately :( – Evan Meredith-Davies Nov 27 '19 at 12:57
  • 1
    @kero It's WordPress. The global namespace already is a radioactive soup. There are of course more "elegant" solutions, but sometimes this is overkill and certainly out of scope here. – maryisdead Nov 27 '19 at 14:06
  • @EvanMeredith-Davies This works. Tested it in a vanilla WordPress installation. global needs to be used in the file/place where you want to access the variable, not where you define it. Your second code snippet, which file exactly is this in? – maryisdead Nov 27 '19 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.