Skip to content

Instantly share code, notes, and snippets.

@halgatewood
Last active October 8, 2019 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halgatewood/2bc479696ede182d9c497aaeec633b20 to your computer and use it in GitHub Desktop.
Save halgatewood/2bc479696ede182d9c497aaeec633b20 to your computer and use it in GitHub Desktop.
WordPress function to get Dark Sky Weather data
<?php
/*
Parameters:
1. Latitude
2. Longitude
3. Format: all, currently, minutely, hourly, daily
4. Dark Sky Secret Key
5. Cache time in seconds (default: 15 minutes)
*/
function get_darksky_data( $lat, $lng, $which = 'all', $key = '', $cache = 900 )
{
$transient_name = 'darksky-' . $which . '-' . $lat . '-' . $lng;
if( get_transient( $transient_name ) )
{
return get_transient( $transient_name );
}
$ping = 'https://api.darksky.net/forecast/' . $key . '/' . $lat . ',' . $lng .'?timezone=' . get_option('timezone_string');
$ping_get = wp_remote_get( $ping );
$data = json_decode( $ping_get['body'] );
// GET CERTAIN DATA
if( strtolower($which) != 'all' AND isset($data->$which)) $data = $data->$which;
// SET CACHE
set_transient( $transient_name, $data, $cache );
return $data;
}
// USAGE
$weather = get_darksky_data( 35.467220, -97.315630, 'hourly' );
echo '<pre>';
print_r($weather);
echo '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment