Search code examples
phpwordpressfunctioninclude

Reusing a PHP variable from a function across files


I have a Wordpress site and I'm looking at 3 relevant files:

  • functions.php
  • header.php
  • index.php (includes header.php)

I'm pulling weather data from an outside feed with a function in functions.php and then trying to display that data in two places - once in header.php (on every page of the site) and once in index.php (a second instance that displays on the home page only). I can get the first instance to display, but I'm having trouble with the second instance

functions.php

function arctic_valley_weather() {
    function get_string_between($string, $start, $end){
        //here's a function that just parses the data. not important
    }

    $fullstring = file_get_contents('http://www.cnfaic.org/library/grabbers/nws_feed.php');
    $parsed = get_string_between($fullstring, 'arctic_valley,', 'marmot,');
    $weatherValues = explode(",",$parsed);
    $dateTime = date_create($weatherValues[0]);

     return array(
      'dateTime' => $dateTime,
      'airTemp' => $weatherValues[1],
      'relHumid' => $weatherValues[2],
      'windSpeed' => $weatherValues[3],
      'windDirection' => $weatherValues[4],
      'windGust' => $weatherValues[5],
    );  
}

header.php

$weatherData = arctic_valley_weather();
echo round($weatherData['airTemp']);

This accurately shows the temperature (rounded). Let's say "18".

Trouble comes in index.php when I want to just duplicate that exact same result:

echo round($weatherData['airTemp']);

This one incorrectly shows "0", even though the initial instance is correctly showing 18.

What could be the reason for this?


Solution

  • It looks like Wordpress includes the header.php in a function body. This means that all variables defined in header.php are out of scope once you leave header.php. You can't access the variable in index.php, footer.php, page.php, etc. One solution is to call your function again. But this would make another request to your external resource and that would probably be a waste. Or you could assign it to the superglobal $GLOBALS array.

    See this similar post: setting variable in header.php but not seen in footer.php

    So you would have to do something like this in your header.php file:

    $GLOBALS['weatherData'] = arctic_valley_weather(); 
    echo $GLOBALS['weatherData'];
    

    And in your index.php file you would do this:

    echo $GLOBALS['weatherData'];