Apr 08 2018
Apr 08, 2018

Weather Alerts API Plugin for WP

Categorised in:

In this article I want to share an experience I had with one of my current projects I am working on. The project consists of a website with Surf Reports, live cameras and other tools for surfers. A very interesting project. I may come up with a case study later but for now I want to talk about one of the features I built for them and this is the Weather Alerts.

So whenever there is any weather alert in the area then on the sidebar is pupping up a small red block like in the example below:

This was done using the National Weather Service API. I built a simple plugin for WP which calls this API and gets the data in a JSON format and then decodes it using a native PHP function, json_decode.

Weather Alerts API documentation.

So, let’s get into it.

This plugin consists of one PHP file. If you have installed WP just go to public_html/wp-content/plugins/ and create a new folder “weather-alerts”, open the new folder and create a new PHP file and paste there the entire code from the end of this article.

Let’s break it down.

The code bellow is a PHP comment. This comment is very important because WordPress engine reads it. That’s how WordPress knows what file from our plugin is the main file and it also shows this information in the Installed Plugins tab on the dashboard.

<?php
	/*
	Plugin Name: Weather Alerts
	Plugin URI: http://ruvictor.com
	Description: This plugin is showing Weather Alerts.
	Author: Victor Rusu
	Author URI: http://ruvictor.com
	Version: 1.0
	Licence: GPLv2
	*/

Below this comment we have an “if” statement which is a security measure checking on a defined constant ‘ABSPATH’. This doesn’t allow anybody to access this file directly using their browser:

//Exit if accessed directly
	if(!defined('ABSPATH')){
		exit;
	}

This security measure is followed by a PHP function which is ruvictor_weather_alert(). If you will pay close attention to the function’s name you will see the prefix of it which is ruvictor_. I used a prefix to make sure this function’s name is unique because sometimes I have installed other plugins on my WP websites which may have functions with the same name and it may cause errors. Please, see the function bellow. I left comments between the lines.

function ruvictor_weather_alert(){
	// Initialize a cURL session
	$ch = curl_init();
	// Assign the Headers
	$header = array('HTTP_ACCEPT: application/atom+xml;version=1', 'Cookie: foo=barrn', 'User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10rn');
	curl_setopt($ch, CURLOPT_URL, "https://api.weather.gov/alerts/active/zone/AKZ201"); # URL to post to
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header ); # custom headers, see above
	$result = curl_exec( $ch ); # run!
	// Decode the result and reassign it to $result variable
	$result = json_decode($result);
	// close the cURL session
	curl_close($ch);
	// Here we check if there is any alert 
	// and if there is at least one then we get the effective date 
	// and check if it is equal to today's date. If it is then we show the headline's value
	// in a div class: weather_alert
	if(substr($result->features[0]->properties->effective, 0,10) == date("Y-m-d")){
		$content = '<div class="weather_alert">' . $result->features[0]->properties->headline . '</div>';
	}else{
		// if the date is different or if there aren’t any alerts then 
		// we assign an empty char so we can return it.
		$content = '';
	}
	return $content;
}
// add_shortcode is a WordPress function which 
// generates a short-code so it can be used to output the data
// from the function located in the second parameter.
add_shortcode('weather_alert', 'ruvictor_weather_alert');
?>

For more information about add_shortcode() please visit codex.wordpress.org

Let’s talk a little bit about this line:

curl_setopt($ch, CURLOPT_URL, "https://api.weather.gov/alerts/active/zone/AKZ201");

The third parameter is a link. This is the API link. At the end of the link we have AKZ201. This is the identification of the location, it’s like a unique ID. A list of USA can be found here: https://alerts-v2.weather.gov/. Make sure you click on the Zone List button if you want to see the locations with their ID. All those numbers next to the states or locations are the amount of alerts with the current effective date.

Another thing I wanted to pay close attention is this “if” statement:

if(substr($result->features[0]->properties->effective, 0,10) == date("Y-m-d")){
		$content = '<div class="weather_alert">' . $result->features[0]->properties->headline . '</div>';
	}else{
		// if the date is different or if there isn't any alerts then 
		// we assign an empty char so we can return it.
		$content = '';
	}

Here we access our data after it was decoded using json_decode function. It was reassigned to the $result variable as an Object. That’s why we access it in this way $result->features[0]->properties->effective. If you know OOP, then this shouldn’t be new to you.

Let’s put everything together and see what we have.

<?php
/*
Plugin Name: Weather Alerts
Plugin URI: http://ruvictor.com
Description: This plugin is showing Weather Alerts.
Author: Victor Rusu
Author URI: http://ruvictor.com
Version: 1.0
Licence: GPLv2
*/
//Exit if accessed directly
if(!defined('ABSPATH')){
	exit;
}
function ruvictor_weather_alert(){
	// Initialize a cURL session
	$ch = curl_init();
	// Assign the Headers
	$header = array('HTTP_ACCEPT: application/atom+xml;version=1', 'Cookie: foo=barrn', 'User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10rn');
	curl_setopt($ch, CURLOPT_URL, "https://api.weather.gov/alerts/active/zone/AKZ201"); # URL to post to
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header ); # custom headers, see above
	$result = curl_exec( $ch ); # run!
	// Decode the result and reassign it to $result variable
	$result = json_decode($result);
	// close the cURL session
	curl_close($ch);
	// Here we check if there is any alert 
	// and if there is at least one then we get the effective date 
	// and check if it is equal to today's date. If it is then we show the headline's value
	// in a div class: weather_alert
	if(substr($result->features[0]->properties->effective, 0,10) == date("Y-m-d")){
		$content = '<div class="weather_alert">' . $result->features[0]->properties->headline . '</div>';
	}else{
		// if the date is different or if there isn't any alerts then 
		// we assign an empty char so we can return it.
		$content = '';
	}
	return $content;
}
// add_shortcode is a WordPress function which 
// generates a short-code so it can be used to output the data
// from the function it has as a second parameter.
add_shortcode('weather_alert', 'ruvictor_weather_alert');
?>

Copy and paste this code in your PHP file.

The next step would be to go on your Dashboard->Plugins->Installed Plugins and there you should find your plugin. Activate it and use your short-code wherever you wish on your website with square brackets like this [weather_alert].

The way this plugin from this tutorial works right now is it checks if there is any alert in the area and if there is at least one with the current effective date then it takes just the first alert and shows it on the page. If you want to show all of them, you need to add a loop and go through all of them. This is just a basic example on how to use the National Weather Service API.

Make sure you add some CSS styling for <div class="weather_alert"></div>.

If you find it difficult I also made a video tutorial on how to build this plugin. You can find it on my YouTube Channel.

For any other questions, feel free to contact me.

Keep on coding!