Skip to content

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

Join me, Shanda, Ed, Tom. They're all chatting about "Using the Yahoo Weather API (in your WordPress themes)" below ›

Read Comments

42 Comments »

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

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

    • 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.

  3. 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….

    • 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']; ?>

  4. 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…

  5. 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…

  6. 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"/>

    • 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

  7. 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!

    • 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

  8. 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

  9. 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

      • 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.

      • 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.

      • It looks like you’re missing the php tags

        Try this.

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

      • 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

  10. 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?

    • 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.

  11. 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.

    • 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.

  12. 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..

  13. Pingback: Displaying the local weather in your Wordpress Theme | Martin Black | Web and Graphic Design | Cambridge, UK
Comments are closed. Let's continue the conversation on Twitter.
css.php