Using the Yahoo Weather API (in your WordPress themes)

When developing our Hyperlocal WordPress theme called The Local Darren came up with the idea of adding the local weather to the themes header. After a bit of research I decided that the Yahoo! Weather api was the best solution.

Before writing the code I Googled around to find something that would speed up development but all the solutions I found were overly complicated and cumbersome. I wanted some small fast code - so decided to write my own.

The process for using the Yahoo Weather API is relatively simple

  1. Work out what you want to request
  2. Request it from the Yahoo servers (grab content from another site)
  3. Parse the text that is sent back and display the relevant parts

The code below is a slightly simplified version of what I used in my WordPress theme, but there's no reason it couldn't be modified to work stand-alone as well - it would only need a few small changes to remove the WordPress dependencies.

<?php
function bm_getWeather ($code = '', $temp = 'c') {

	$file = 'http://weather.yahooapis.com/forecastrss?p=' . $code . '&u=' . $temp;
	
	$request = new WP_Http;
	$result = $request->request($file);

	if (isset($result->errors)) {
		return FALSE;
	}
	
	$data = $result['body'];
			
	$output = array (
		'temperature' => bm_getWeatherProperties('temp', $data),
		'weather' => bm_getWeatherProperties('text', $data),
		'weather_code' => bm_getWeatherProperties('code', $data),
		'class' => 'weatherIcon-' . bm_getWeatherProperties('code', $data),
	);
	
	return $output;

}

function bm_getWeatherProperties ($needle, $data) {

	$regex = '<yweather:condition.*' . $needle . '="(.*?)".*/>';
	preg_match($regex, $data, $matches);
	
	return $matches[1];
	
}

One thing to note, that is not in the code above, is that Yahoo! places an API usage limit on the requests by IP address, so to be able to get consistent usage you need to add some sort of data storage, to keep the information safe for X seconds and reduce the requests to their servers. I have a series of posts on WordPress caching planned so I will save these posts for another time.

Break it Down

The bm_getWeather function grabs the content as text from the Yahoo website (using the Http get stuff I mentioned recently) and then reads through the results grabbing the bits it is most interested in. The bm_getWeatherProperties function is a simple reusable way to read the data I need from the text file that was downloaded. It uses a regular expression to grab the meta data Yahoo! are returning and then inserts it into an array.

Using it

Usage is simple, pass the 'code' and the 'temperature' to the bm_getWeather function, and then get an array of info back to use and display however you fancy. The code should be the location code as used by Yahoo! to specify where you are based. The temperature (temp) should be either 'c' or 'f' based upon what temperature measurement you want the weather returned in.

To get the location code you should search for your location on Yahoo! weather and then area code from the resultant URL. For example the url: http://weather.yahoo.com/forecast/UKXX0085.html would give you the code UKXX0085 (which is actually the code for London, England).

A simple request would look like this:

$weather = bm_getWeather('IDXX0022', 'c');
print_r($weather);

and give results like this:

Array (
[temperature] => 28
[weather] => Partly Cloudy
[weather_code] => 30
[class] => weatherIcon-30
)

Share This...

About The Author

Ben Gillbanks

Web Designer, Video Gamer, Blogger, and part time Entrepreneur. Read More

42 thoughts on “Using the Yahoo Weather API (in your WordPress themes)

  • Reply ›
    Rilwis

    Nice tutorial. Your code is minimalist and optimized. It can be easily integrated into any website with PHP. Thank you very much for sharing.

    March 15, 2010

  • Reply ›
    dan

    How would I implement this on a normal website? I'm new to rss/php so any help would be greatly appreciated!

    March 26, 2010

    • Reply ›
      Ben

      You'd need to add some additional code for reading the content from another website. This functionality is built into WordPress but it shouldn't be hard to do. Perhaps I could do another post with info on doing this for a standalone site.

      March 26, 2010

  • Reply ›
    Stephan

    getting all those things by wordpress isn't very cool is it?

    I'm starting to feel much more for a combination of wordpress and jquery....

    So why nog request the weather by jsonp??
    http://www.ibm.com/...eb/library/wa-aj-jsonp2/index.html

    This might be cool....

    April 7, 2010

  • Reply ›
    Stephan

    Sorry my reply before doesn't tell the real story.

    you could also use the following link.

    http://developer.yahoo.com/...bles.org/alltableswithkeys

    This is a xml data store. You can also use jsonp. So this uses the clients ip adress.

    I will try to create some sort of wordpress plugin in the near future.

    April 7, 2010

  • Reply ›
    Mat

    I have been developing for iPhone weather apps and have been using this free weather API (http://www.worldweatheronline.com/weather-api.aspx) in my commercial apps. It supports JSON and JSON-P and has quite extended global weather forecast.

    April 14, 2010

  • Reply ›
    Ed

    Can you tell me where to add the above codes? I know the top code goes in wordpress functions.php but the other two sets of codes..where do I add them? Why not explain where to add all codes to help? Thanks....

    June 23, 2010

    • Reply ›
      Ben

      Hi Ed - the top two functions goes in your themes functions.php. The other bit of code can go inside your theme and be used in any way you see fit.

      All you need to do is use $weather = bm_getWeather('IDXX0022', 'c'); in your theme to get the data and then print the properties you want to display. Eg

      The temperature is <?php echo $weather ['temperature']; ?>

      June 24, 2010

  • Reply ›
    Ed

    Where do I add this $weather = bm_getWeather('IDXX0022', 'c'); 1. in my functions.php or the theme file I want to use it...trying to getting this in my header.php...I add that top code into functions but still a bit confused...thanks for the help...I'm new to wordpress...

    June 25, 2010

  • Reply ›
    ed

    In case your new to wordpress:

    1. Add the following code to functions.php file:

    request($file);
    
    	if (isset($result->errors)) {
    		return FALSE;
    	}
    
    	$data = $result['body'];
    
    	$output = array (
    		'temperature' => bm_getWeatherProperties('temp', $data),
    		'weather' => bm_getWeatherProperties('text', $data),
    		'weather_code' => bm_getWeatherProperties('code', $data),
    		'class' => 'weatherIcon-' . bm_getWeatherProperties('code', $data),
    	);
    
    	return $output;
    
    }
    
    function bm_getWeatherProperties ($needle, $data) {
    
    	$regex = '';
    	preg_match($regex, $data, $matches);
    
    	return $matches[1];
    
    }

    2. Add the following in which theme file you want to show the weather:
    (ie. Header.php)

    Dover, DE 

    Demo Click Here:
    http://www.wolverinesocceracademy.com

    Thanks Ben! Keep up the great work with the site...

    June 25, 2010

  • Reply ›
    Jeremy Davis

    Not sure if the Yahoo API got changed or if I didn't do something right, but I just wanted to drop a comment incase someone else has this issue.

    The parameter used to request a locations weather is 'w' not 'p'.

    So, http://weather.yahooapis.com/forecastrss?p=' . $code . '&u=' . $temp;

    Should be http://weather.yahooapis.com/forecastrss?w=' . $code . '&u=' . $temp;

    Hope that helps.

    July 15, 2010

  • Reply ›
    Nirok

    Yeah Jeremy is correct works if you replace the 'p' with 'w'. I also replaced the class so that it just outputted the number. Then placed this in my template image (I added my town attributes to the bm_getWeather function in functions.php):

    <img src="http://l.yimg.com/a/i/us/we/52/.gif"/>

    September 3, 2010

    • Reply ›
      Ben

      Just read the api docs. It seems p still works but won't in the future. I'm going to have to update my theme now :) Thanks again for pointing this out

      September 3, 2010

  • Reply ›
    Shanda

    Thanks for creating this! Absolutely perfect for what I needed. Kudos!!

    October 19, 2010

  • Reply ›
    Colin Hall

    Excellent, now I've just got to work a way of incorporating it into my idea for wine vintage prediction ... The future is prediction ;-) ))

    November 22, 2010

  • Reply ›
    Joey

    Super cool tool, gang! We have been getting more requests for weather on pages and this will come in handy.

    December 29, 2010

  • Reply ›
    Tom

    Hi! Thanks for the code!

    Quick question: I'm placing $weather = bm_getWeather('UKXX0085', 'c'); into by theme (into header.php), followed by Today: and I placed the two functions into the functions file, but nothing is printing after "Today:".

    Any ideas? Thanks!

    January 20, 2011

    • Reply ›
      Ben

      Can't really say why it isn't working without seeing the implementation. I would suggest turning on error_reporting and seeing what it throws out

      January 20, 2011

  • Reply ›
    Shanda

    Hi Tom,

    $weather = bm_getWeather('UKXX0085', 'c');

    is only setting the weather location. You are looking to include this:

    Today: °

    That is calling the $weather and the data for the temperature.

    Let me know if you need more help. And if this doesn't work. Post what you placed in your functions and what you placed in your header.

    Shanda

    January 20, 2011

  • Reply ›
    Shanda

    Sorry Coding fail.... Shall I try again?
    Hi Tom,

    $weather = bm_getWeather('UKXX0085', 'c');

    is only setting the weather location. You are looking to include this:

    Today: °

    That is calling the $weather and the data for the temperature.

    Let me know if you need more help. And if this doesn't work. Post what you placed in your functions and what you placed in your header.

    Shanda

    January 20, 2011

    • Reply ›
      Shanda

      lol!! It doesnt like the php anyways.

      Today: [ php here ] echo $weather ['temperature']; [ / end php ]

      January 20, 2011

      • Ben

        you can use the &lt; tag to display brackets :)

        January 20, 2011

      • Shanda

        Haha. But spamming it was so much fun. :D I tried to see if I can delete them but eh. Failed again. Thanks I will remember that.

        January 20, 2011

      • Tom

        Hi!

        Thanks for the quick replies.

        What I have is:

        [code]
        $weather = bm_getWeather('UKXX0085', 'c');
        [/code]

        followed by

        [code]

        Today: [ php bit ] echo $weather ['temperature']; [ / end php ]

        [/code]

        But the $weather = ... is just showing up as text.

        Here's my functions.php file:

        [code]
        request($file);

        if (isset($result->errors)) {
        return FALSE;
        }

        $data = $result['body'];

        $output = array (
        'temperature' => bm_getWeatherProperties('temp', $data),
        'weather' => bm_getWeatherProperties('text', $data),
        'weather_code' => bm_getWeatherProperties('code', $data),
        'class' => 'weatherIcon-' . bm_getWeatherProperties('code', $data),
        );

        return $output;

        }

        function bm_getWeatherProperties ($needle, $data) {

        $regex = '';
        preg_match($regex, $data, $matches);

        return $matches[1];

        }

        ?>
        [/code]

        You can view the site and see what's going on by visiting testing.ruralnl.ca.

        January 20, 2011

      • Shanda

        It looks like you're missing the php tags

        Try this.

        <?php $weather = bm_getWeather('UKXX0085', 'c'); ?>
        Today: <?php echo $weather ['temperature']; ?> °

        January 20, 2011

      • Tom

        Thanks. I added in the php but it still isn't spitting out any information.

        Any more ideas?

        January 20, 2011

      • Shanda

        Hi Tom,

        I just viewed your site and it looks like you have it working now. -3 is cold. :D Let me know if you need anymore help. Thanks Ben, again for developing this. I use this on my client's sites and I think it would be great as a plugin. You can view the site I placed it on here http://www.palmgardensonline.com

        January 20, 2011

      • Tom

        I did get it working! And it's -7 now... brr!

        Thanks for your help folks!

        January 21, 2011

  • Reply ›
    Ed

    Do you know why the temperature is not showing? It's not even working on your site? ugh...

    Worked great before...let me know if you have a fix?

    August 19, 2011

    • Reply ›
      Ben

      This code was written over a year ago, and it seems Yahoo! have changed the api (not for the first time! :( ) - I have no idea what the new code is and will have to do some testing to work it out.

      August 19, 2011

  • Reply ›
    pinigenai

    Thanks for information. Its working!

    April 1, 2012

  • Reply ›
    Steven

    Hey folks.

    Got this code working fine. Was wondering if anyone has got custom images working for this code though? I'd love to be able to have a sprite (or separate images) for each weather condition and have them display on my site. Any help would be awesome.

    April 11, 2012

    • Reply ›
      Ben

      I am afraid I don't have any images for this but it would be great if someone knew of anything. The Yahoo! ones are a bit rubbish looking.

      April 12, 2012

  • Reply ›
    Steven

    Hey Ben,

    Sorry what I was meaning was had anyone had any success with writing a function that switched out the yahoo images with custom images? I've seen it done before using the condition codes..

    April 13, 2012

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Websites linking here

  1. Favicon for http://www.google.com/s2/favicons?domain=www.wphardcore.com Follow Friday: Ben Gillbanks - WordPress Hardcore
  2. Favicon for http://www.google.com/s2/favicons?domain=mblackdesign.co.uk Displaying the local weather in your Wordpress Theme | Martin Black | Web and Graphic Design | Cambridge, UK
  3. Favicon for http://www.google.com/s2/favicons?domain=www.binarymoon.co.uk Using cURL to Read the Contents of a Web Page

My Projects

TimThumb - Image Resize Script TimThumb

Image Resize Thumbnail Script

WPVote - WordPress Social Voting WPVote.com

WordPress Social Voting Site

About me

About BenMy name is Ben Gillbanks. I'm a lover of Video Games, WordPress, Web Development and everything in between.

I have been working on the internet since 1998, and working with computers even longer. I am a hardcore Nintendo fanboy and have owned most of their consoles at one stage or another.

Read more about me on my about page.

Random Link-outs

Keep Updated

Subscribe to RSS

Stay Updated

Binary Moon

WordPress and Web Development › home of Ben Gillbanks