joelkrause
10/9/2019 - 10:06 PM

Getting OpenWeatherMap with WordPress Transients

Getting OpenWeatherMap with WordPress Transients

<?php
function setWeatherCelcius() {
    $curl = curl_init();

    curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.openweathermap.org/data/2.5/weather?id=2208305&APPID=db6889d62a3a881cb6c204dc256c0bae&units=metric",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache"
    ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);
    $response = json_decode($response, true); //because of true, it's in an array

    $transient = 'weather';
    $value = $response;
    $expiration = HOUR_IN_SECONDS / 2;

    set_transient( $transient, $value, $expiration );
}
setWeatherCelcius();
<?php
function showWeather(){
    $weather = get_transient('weather');
    $temperature = $weather['main']['temp'];
    $description = $weather['weather'][0]['description'];
    $icon = $weather['weather'][0]['icon'];
    $code = $weather['weather'][0]['id'];
    $desc = get_field('weather_'.$code,'options');

    $html = round($temperature).'&#186; and <span class="description">'.$description.'</span>';
    echo $html;
}