Simple weather in WordPress without a plugin
Sometimes a site needs one or two weather values, for example the temperature or the wind speed and direction, with its own styles. A weather plugin will not help much here: it brings its own widget and markup. A small function is a better solution.
Problem: Output weather data in WordPress without a plugin.
Solution: First get an API key from a weather service, for example openweathermap.org (it has a free plan). Then request the data from its API in PHP and cache it.
Step 1. The current weather
<?php
// Get the current weather from openweathermap.org
function get_weather( $coordinates ) {
$api_key = 'YOUR_API_KEY';
$url = add_query_arg( array(
'lat' => $coordinates['lat'],
'lon' => $coordinates['lng'],
'units' => 'imperial',
'appid' => $api_key,
), 'https://api.openweathermap.org/data/2.5/weather' );
$response = wp_remote_get( $url, array( 'timeout' => 10 ) );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
return false;
}
$data = json_decode( wp_remote_retrieve_body( $response ), true );
return array(
'temperature' => round( $data['main']['temp'] ),
'description' => ucfirst( $data['weather'][0]['description'] ),
'wind_speed' => $data['wind']['speed'],
'wind_deg' => $data['wind']['deg'],
'icon' => 'https://openweathermap.org/img/wn/' . $data['weather'][0]['icon'] . '@2x.png',
);
}
Units of measurement:
units=imperial— Fahrenheit, wind in miles per hour;units=metric— Celsius, wind in meters per second.
Step 2. Cache the result
There is no need to call the API on every page view: the weather does not change every second, and the free plan has a limit on calls. Keep the result in a transient for 30 minutes:
<?php
function get_weather_cached( $coordinates ) {
$key = 'weather_' . md5( $coordinates['lat'] . ',' . $coordinates['lng'] );
$weather = get_transient( $key );
if ( false === $weather ) {
$weather = get_weather( $coordinates );
if ( $weather ) {
set_transient( $key, $weather, 30 * MINUTE_IN_SECONDS );
}
}
return $weather;
}
Step 3. Output
For example, as a shortcode [weather lat="40.71" lng="-74.01"]:
<?php
add_shortcode( 'weather', function ( $atts ) {
$atts = shortcode_atts( array( 'lat' => '', 'lng' => '' ), $atts );
$weather = get_weather_cached( $atts );
if ( ! $weather ) {
return '';
}
return sprintf(
'<div class="weather"><img src="%s" alt="%s" width="50" height="50"><span class="weather__temp">%d°F</span> <span class="weather__desc">%s</span></div>',
esc_url( $weather['icon'] ),
esc_attr( $weather['description'] ),
$weather['temperature'],
esc_html( $weather['description'] )
);
} );
Update (2020): OpenWeatherMap added the One Call API, which returns the current weather and a daily forecast in one request: https://api.openweathermap.org/data/2.5/onecall?lat=...&lon=...&exclude=minutely,hourly&units=imperial&appid=.... The forecast is in $data['daily'], where every day has dt, temp (an array: day, min, max…) and weather.
Update (2024): One Call 2.5 was shut down. Version 3.0 (/data/3.0/onecall, same parameters) needs a separate “One Call by Call” subscription, which includes 1,000 free calls per day. The current weather endpoint from step 1 still works with the free key.
Sources: