RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (6.59%*) • Fixed: 5.39% (6.59%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.48%*) • Investment PI: 5.39% (6.59%*)

Embed Weather Underground Forecasts with WordPress Shortcode or PHP

Embed Weather Underground Forecasts with WordPress Shortcode or PHP

Weather Underground, owned by The Weather Channel since 2012, is a commercial weather service that provides real-time weather information and reports for most major cities across the world... as well as providing services for newspapers and websites that syndicate their content. While the data is sourced mainly from official sources, they also aggregate feeds from users' that upload their own localized data.

Note: The WeatherUnderground API has undergone changes and we're yet to catch up. Code will be updated soon.

This is the first of a few articles detailing different ways of rendering weather forecasts. Since Weather Underground is a commercial service, we'll follow up on this post detailing how to display weather details with the more permissive OpenWeatherMap .

The examples on this page are just that - examples. Don't expect anything fancy. If you're a client, keep in mind that if weather details are required we'll always format the data to seamlessly integrate with your website. For the purposes of the examples we've rendered the results in text boxes.

The Result

The following is an example of a 4-day day/night forecast for Sydney, Australia (results are cached for 12 hours). Because defaults were defined as shortcode attributes, we've used just [weatherunderground] to return the result.

If you were to include just the most recent forecast (either day or night), use [weatherunderground period="1"]. Each period essentially represents a half day.

WordPress Shortcode

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
 Embed Weather Underground Forecasts with WordPress Shortcode or PHP
4
 http://www.beliefmedia.com/weather-underground-forecasts
5
*/
6
 
7
8
 
9
  $atts = shortcode_atts(array(
10
    'apikey' => 'xxxxxxxxxxxxxxxx',
11
    'country' => 'Australia',
12
    'city' => 'Sydney',
13
    'icons' => 'i',
14
    'period' => '8',
15
 
16
    /* Text box */
17
    'width' => '90%',
18
 
19
    'cache' => 3600 * 12
20
  ), $atts);
21
 
22
 $transient = 'bmwu_' . md5(serialize($atts));
23
 $cached =  get_transient($transient);
24
 
25
 if ($cached !== false ) {
26
  return $cached;
27
 
28
  } else {
29
 
30
   $data = file_get_contents('http://api.wunderground.com/api/' . $atts['apikey'] . '/geolookup/conditions/forecast/q/' . $atts['country'] . '/' . $atts['city'] . '.json');
31
   if ($data !== false) $data = json_decode($data, true);
32
     else return 'Error retrieving Weather. Check API Key';
33
 
34
   $forecast = $data['forecast']['txt_forecast']['forecastday'];
35
   if (count($forecast) == '0') return 'Empty forecast. Invalid';
36
 
37
   /* Station used for attribution link */
38
   $station = $data['current_observation']['forecast_url'];
39
 
40
   $i = 1;
41
   foreach ($forecast AS $weather) {
42
 
43
     $title = $weather['title'];
44
     $txt = $weather['fcttext_metric'];
45
     $pop = $weather['pop'];
46
     $icon = $weather['icon'];
47
 
48
     $iconurl = 'http://icons.wxug.com/i/c/' . $atts['icons'] . '/' . $icon . '.gif';
49
     $rain = ($pop != '0') ? ' Probability of rain: ' . $pop . '%.' : '';
50
 
51
     if ($i <= $atts['period']) {
52
       $return .= '
53
 
54
<div style="text-align:left; margin: 0 auto; width: ' . $atts['width'] . '; font-weight: bold;">' . $title . '</div>';
55
       $return .= '<div style="width: ' . $atts['width'] . '; margin: auto; border: #FFCC00 1px solid">
56
<div style="padding: 8px 30px 10px 30px; color: #000000; padding: 15px 30px 18px 65px; background: #ffffff url(' . $iconurl . ') no-repeat 10px 50%;">' . trim($txt . '. ' . $rain) . '</div>
57
</div>';
58
     }
59
 
60
     $i++;
61
   }
62
 
63
  /* Attribution */
64
  $return .= '<div style="text-align:right; margin: 0 auto; width: ' . $atts['width'] . '">Weather sourced from <a href="' . $station . '" target="_blank" rel="noopener noreferrer">WeatherUnderground</a></div>';
65
 
66
  set_transient($transient, $return, $atts['cache']);
67
  return $return;
68
 }
69
}
70
add_shortcode('weatherunderground', 'beliefmedia_weatherunderground_forecast');

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

Shortcode Attributes

apikey

An API key is required to use the WU service, and a payment plan is generally required for any commercial usage. Sign up here .

country

The JSON request for a specific location generally takes the form of Country(Region)/City(orLocation).json (with underscores instead of spaces). You may have to play around on the WU website to ensure you request weather in the correct format. The shortcode for a specific location is as follows: [weatherunderground country="Australia" city="Sydney"]

city

The JSON request for a specific location generally takes the form of Country(Region)/City(orLocation).json (with underscores instead of spaces). You may have to play around on the WU website to ensure you request weather in the correct format. The shortcode for a specific location is as follows: [weatherunderground country="Australia" city="Sydney"]

icons

A number of icons sets are available by default from the WU website . Alternatively, you can create your own... or use any of the sets created by others. The icons available at the time of writing are published here on WU's website. Icons are referenced with the attribute of icons="a", icons="b", icons="c", icons="d", icons="e", icons="f", or icons="g", and so on (up until 'k').

period

Each period is essentially a 12-hour block (or half day). So, to display the next 24 hours of weather we'll use [weatherunderground period="2"]. WU generally returns an 8-period (or 4-day) block. If you're planning on returning a single day forecast, it'd be prudent to render both half-days into the same container.

cache

The cache is the period of time to store the results of your query locally. I've used 12 hours but you might consider using a shorter timeframe so that you don't miss out on new data when it becomes available.

PHP Function

Used outside of WordPress the following may be used. Usage of Simple Cache is required to avoid repeated requests to WU.

1
<?php 
2
include('../simple-cache/cache.inc.php');
3
 
4
/*
5
 Embed Weather Underground Forecasts with WordPress Shortcode or PHP
6
 http://www.beliefmedia.com/weather-underground-forecasts
7
*/
8
 
9
function beliefmedia_weatherunderground_forecast($location, $args = '') {
10
 
11
  $atts = array(
12
    'apikey' => 'xxxxxxxxxxxxxxxx',
13
    'icons' => 'i',
14
    'period' => '8',
15
    'width' => '90%',
16
    'cache' => 3600 * 12
17
  );
18
 
19
 /* City & Country */
20
 $location = explode(',', $location);
21
 $city = str_replace(' ', '_', trim($location['0']));
22
 $country = str_replace(' ', '_', trim($location['1']));
23
 
24
 /* Overwrite the option defaults */
25
 if ($args != '') $atts = array_replace($atts, array_filter($args));
26
 
27
 $transient = 'bmwunderground_' . md5(serialize($atts));
28
 $cached =  beliefmedia_get_transient($transient, $atts['cache']);
29
 
30
 if ($cached !== false ) {
31
  return $cached;
32
 
33
  } else {
34
 
35
   $data = file_get_contents('http://api.wunderground.com/api/' . $atts['apikey'] . '/geolookup/conditions/forecast/q/' . $country . '/' . $city . '.json');
36
   if ($data !== false) $data = json_decode($data, true);
37
     else return 'Error retrieving Weather. Check API Key';
38
 
39
   $forecast = $data['forecast']['txt_forecast']['forecastday'];
40
   if (count($forecast) == '0') return 'Empty forecast. Invalid';
41
 
42
   /* Station used for attribution link */
43
   $station = $data['current_observation']['forecast_url'];
44
 
45
   $i = 1;
46
   foreach ($forecast AS $weather) {
47
 
48
     $title = $weather['title'];
49
     $txt = $weather['fcttext_metric'];
50
     $pop = $weather['pop'];
51
     $icon = $weather['icon'];
52
 
53
     $iconurl = 'http://icons.wxug.com/i/c/' . $atts['icons'] . '/' . $icon . '.gif';
54
     $rain = ($pop != '0') ? ' Probability of rain: ' . $pop . '%.' : '';
55
 
56
     if ($i <= $atts['period']) {
57
       $return .= '
58
 
59
<div style="text-align:left; margin: 0 auto; width: ' . $atts['width'] . '; font-weight: bold;">' . $title . '</div>';
60
       $return .= '<div style="width: ' . $atts['width'] . '; margin: auto; border: #FFCC00 1px solid">
61
<div style="padding: 8px 30px 10px 30px; color: #000000; padding: 15px 30px 18px 65px; background: #ffffff url(' . $iconurl . ') no-repeat 10px 50%;">' . trim($txt . '. ' . $rain) . '</div>
62
</div>';
63
     }
64
 
65
     $i++;
66
   }
67
 
68
  /* Attribution */
69
  $return .= '<div style="text-align:right; margin: 0 auto; width: ' . $atts['width'] . '">Weather sourced from <a href="' . $station . '" target="_blank" rel="noopener noreferrer">WeatherUnderground</a></div>';
70
 
71
  beliefmedia_set_transient($transient, $return);
72
  return $return;
73
 }
74
}
75
 
76
/* Usage */
77
echo beliefmedia_weatherunderground_forecast($location = 'Sydney,Australia');
78
 
79
/* With arguments */
80
$args = array('period' => '3', 'icons' => 'j');
81
echo beliefmedia_weatherunderground_forecast($location = 'Melbourne,Australia', $args);

Considerations

  • Registration to the WU API is required before you can access data. The returned JSON data via a normal location request is over 1000 lines with enormous amounts of data (some of which you might consider using). For that reason, additional articles will be required to show how other data can be displayed in different ways.
  • Attribution with a link back to the original weather forecast is required as per WU's terms and conditions.

Download

Not currently available.

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment