ClimaCell

FREEMIUM
Verified
Durch Tomorrow.io | Aktualisiert vor 5 Monaten | Weather
Popularität

0.5 / 10

Latenz

958ms

Service Level

0%

Zurück zu allen Tutorials (1)

How to Call an API from WordPress (in a Plugin)

<h2>How to Integrate an External API in WordPress</h2>
How do you call an API from WordPress?  A great way to do that is by using a Plugin (<a href=“https://rapidapi.com/blog/integrate-external-api-wordpress/”>or directly in a page</a>).  This can populate a widget that you can put anywhere in your theme.

About 1 out of three websites on the internet today use WordPress, according to <a href=“https://w3techs.com/technologies/overview/content_management”>W3Techs.</a>

That means if you’ve ever looked at a website, there’s a good chance it was a WordPress site.  But you already have one, so you know it is popular.

One of the great things about WordPress is the plugins available for download.  They are all designed with the intent of expanding the capability of the site. Plugins do that without changing any of the core code.  This is also the reason to <a href=“https://rapidapi.com/blog/how-to-use-an-api/”>call APIs</a> - to increase the number of features the host site can provide end-users.

For this tutorial, there is a WordPress article that explains in detail how to <a href=“https://codex.wordpress.org/Writing_a_Plugin”>create a plugin</a>.  If you want to know everything about the topic, take a break and read there first. Come back here when you’re ready to walk through a simple example from beginning to end.

Let’s add the air quality for a given location (Los Angeles, California) to a widget you can display on your blog.  The API we’ll be using is <a href=“https://rapidapi.com/ClimaCell/api/climacell”>ClimaCell</a> <a href=“https://rapidapi.com/blog/access-global-weather-data-with-these-weather-apis/”>Weather API</a> and it includes air quality as one of its available parameters.
<h3>TL;DR: How to Call a 3rd Party API in WordPress</h3>
<ol>
<li><strong>Get an API Key for an API</strong></li>
<li><strong>Create a Plugin to add a widget</strong></li>
<li><strong>Customize your Plugin with API</strong></li>
<li><strong>Use the WordPress Admin to add the widget</strong></li>
</ol>
<h3>Prerequisites to call an API from WordPress</h3>
Before following the steps below you’ll need the following:
<ul>
<li>A WordPress Site</li>
<li>A RapidAPI account</li>
</ul>
Setting up a WordPress site is a simple point and click process at many web hosts, and that is the context of this article.  So it will be assumed you have a WordPress site ready to work with.  Signing up for a RapidAPI account is also a simple (and free) process - simply click the “Sign Up” button at <a href=“https://rapidapi.com”>Rapidapi.com</a>.

Here are the main steps we will follow to integrate an API with WordPress through a Plugin:
<ol>
<li>Get an API key for the API</li>
<li>Create a Plugin for adding a widget to your WordPress site</li>
<li>Customize your plugin with your API key and specific information you want to display in the widget</li>
<li>Use the WordPress Admin Area to place the widget on your site where you want it within your theme</li>
</ol>
Now let’s go through the steps in more detail:
<h3>1. Get an API key for the API</h3>
First of all, how much does the ClimaCell API cost?  It can be free if you make a small number of calls.  Here are the details:

<a href=“https://rapidapi.com/ClimaCell/api/climacell/pricing”><img class=“alignnone size-large wp-image-4285” src=“https://rapidapi.com/blog/wp-content/uploads/2020/04/ClimaCell-API-Pricing-1024x593.png” alt=“ClimaCell API Pricing” width=“1024” height=“593” /></a>

In order to get an API Key for the ClimaCell API, go to the <a href=“https://rapidapi.com/ClimaCell/api/climacell/pricing”>ClimaCell pricing page</a> and click on one of the blue Select Plan buttons.  Then go to the <a href=“https://rapidapi.com/ClimaCell/api/climacell/endpoints”>ClimaCell Endpoints</a> page and you will see your X-RapidAPI-Key populated in the Header Parameters section of the API test area.
<h3>2. Create a Plugin for adding a widget to your WordPress site</h3>
Next, you can use some sample code to create a new plugin for WordPress.  To do that, follow these steps:
<ol>
<li>Save the following code in a file called weather-widget-plugin.php</li>
<li>Place the <a href=“https://rapidapi.com/blog/how-to-use-an-api-with-php/”>PHP</a> file into a folder called weather-widget-plugin.</li>
<li>Once you have the file in that folder, compress the folder into a file called weather-widget-plugin.zip.</li>
<li>Then log in to your WordPress admin area and go to Plugins->Add New and click on the Upload Plugin button.  Browse and select the zip file to upload it.</li>
</ol>
<strong>Plugin file weather-widget-plugin.php:</strong>
<pre class=“EnlighterJSRAW” data-enlighter-language=“php”><?php
/*
Plugin Name: Weather Widget Plugin
Description: Show weather details in a widget
Version: 0.17
*/

// Register and load the widget
function weather_load_widget() {
register_widget( ‘weather_widget’ );
}
add_action( ‘widgets_init’, ‘weather_load_widget’ );

// The widget Class
class weather_widget extends WP_Widget {

function __construct() {
parent::__construct(

  // Base ID of your widget
  'weather_widget',

  // Widget name will appear in UI
  __('Weather Widget', 'weather_widget_domain'),

  // Widget description
  array( 'description' =&gt; __( 'Show Weather Details in a Widget', 'weather_widget_domain' ), )
);

}

// Creating widget front-end view
public function widget( $args, $instance ) {
$title = apply_filters( ‘widget_title’, $instance[‘title’] );

//Only show to me during testing - replace the Xs with your IP address if you want to use this
//if ($_SERVER['REMOTE_ADDR']==="xxx.xxx.xxx.xxx") {

  // before and after widget arguments are defined by themes
  echo $args['before_widget'];
  if ( ! empty( $title ) ) echo $args['before_title'] . $title . $args['after_title'];

  // This is where you run the code and display the output
  $curl = curl_init();
  $url = "https://climacell-microweather-v1.p.rapidapi.com/weather/nowcast?fields=epa_aqi&amp;lat=34.0201598&amp;lon=-118.692597";

  curl_setopt_array($curl, array(
  	CURLOPT_URL =&gt; $url,
  	CURLOPT_RETURNTRANSFER =&gt; true,
  	CURLOPT_FOLLOWLOCATION =&gt; true,
  	CURLOPT_ENCODING =&gt; "",
  	CURLOPT_MAXREDIRS =&gt; 10,
  	CURLOPT_TIMEOUT =&gt; 30,
  	CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1,
  	CURLOPT_CUSTOMREQUEST =&gt; "GET",
  	CURLOPT_HTTPHEADER =&gt; array(
  		"x-rapidapi-host: climacell-microweather-v1.p.rapidapi.com",
  		"x-rapidapi-key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  	),
  ));

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    //Only show errors while testing
  	//echo "cURL Error #:" . $err;
  } else {
    //The API returns data in JSON format, so first convert that to an array of data objects
    $responseObj = json_decode($response);

    //Gather the air quality value and timestamp for the first and last elements
    $firstEPAAQI = "&lt;strong&gt;".$responseObj[0]-&gt;epa_aqi-&gt;value."&lt;/strong&gt;";
    $firstTime = date("Y-m-d H:i:s T",strtotime($responseObj[0]-&gt;observation_time-&gt;value));
    $numResults = count($responseObj);
    $lastEPAAQI = "&lt;strong&gt;".$responseObj[$numResults-1]-&gt;epa_aqi-&gt;value."&lt;/strong&gt;";
    $lastTime = date("Y-m-d H:i:s T",strtotime($responseObj[$numResults-1]-&gt;observation_time-&gt;value));

    //This is the content that gets populated into the widget on your site
    echo "The &lt;a href='https://www.airnow.gov/index.cfm?action=aqibasics.aqi'&gt;air quality EPA score&lt;/a&gt; ".
          "is currently $firstEPAAQI at $firstTime and is forecasted to be $lastEPAAQI at $lastTime &lt;br&gt;";
  }

  echo $args['after_widget'];

//} // end check for IP address for testing

} // end public function widget

// Widget Backend - this controls what you see in the Widget UI
// For this example we are just allowing the widget title to be entered
public function form( $instance ) {
if ( isset( $instance[ ‘title’ ] ) ) {
$title = $instance[ ‘title’ ];
} else {
$title = __( ‘New title’, ‘wpb_widget_domain’ );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( ‘title’ ); ?>"><?php _e( ‘Title:’ ); ?></label>
<input class=“widefat” id="<?php echo $this->get_field_id( ‘title’ ); ?>" name="<?php echo $this->get_field_name( ‘title’ ); ?>" type=“text” value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
}

// Updating widget - replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance[‘title’] = ( ! empty( $new_instance[‘title’] ) ) ? strip_tags( $new_instance[‘title’] ) : ‘’;
return $instance;
}
} // Class weather_widget ends here
?>
</pre>
 

Save the PHP file into a folder and then compress it to a zip file. In the Wordpress Admin area this is the Add Plugin interface:

<img class=“alignnone size-full wp-image-4286” src=“https://rapidapi.com/blog/wp-content/uploads/2020/04/Add-Plugin-to-WordPress.png” alt=“Add Plugin to WordPress” width=“885” height=“327” />

This is how the interface will look after uploading the plugin:

<img class=“alignnone size-full wp-image-4287” src=“https://rapidapi.com/blog/wp-content/uploads/2020/04/installing-homemade-plugin.png” alt=“Installing custom wordpress plugin” width=“650” height=“189” />

Before you click the Activate Plugin button, you’ll need to modify the plugin to meet your needs.
<h3>3. Customize your plugin with your API key and specific information you want to display in the widget</h3>
First, you’ll need to replace the Xs in the code with your <a href=“https://rapidapi.com/blog/api-glossary/api-key/”>RapidAPI key</a> on the line starting with this: “x-rapidapi-key”.  Then review what will be printed in your new widget in the widget function of the weather_widget class.

In order to update your plugin after uploading it, you’ll need to upload a new file.  You can use an FTP client like <a href=“https://filezilla-project.org/”>Filezilla</a> or you can use your web host’s file manager.  What you are looking for is the wp-content/plugins/weather-widget-plugin/ directory for your WordPress site.

To update your plugin you can edit the file locally in your favorite editor and then upload it to that directory.  This will overwrite the PHP file which is there already.  However, in order for WordPress to update its version of the file (in case you have any type of caching setup for your site), you will need to change the ‘version’ of the plugin.

To update your version, change the 5th line of the file that looks like this - Version: 0.17.  While developing this example I started from 0.1 and every time I made a change I updated the version, so this is the 17th version of the file.  You can use your own version system.  I started at 0.1 because I would consider version 1 to be a ‘release’ version.  But you can start at 1 or even 100 if you want!

Do you want to show air quality for a different location?  Search for any location you want in <a href=“https://rapidapi.com/blog/google-maps-api-python/”>google maps</a> and then look for the latitude and longitude in the URL.  For example, when I searched for Los Angeles, CA I was taken to a page with an address like this:

https://www.google.com/maps/place/Los+Angeles,+CA/@34.0201597,-118.6926119,10z/

The 2 numbers after the @ symbol in the <a href=“https://rapidapi.com/blog/url-vs-url/”>URL</a> are latitude, longitude (34.0201597,-118.6926119 for this URL).  That’s how I populated those required inputs to the ClimaCell API.  You can choose any location you like to come up with your own coordinates for your plugin.

Also, you might want to show the forecast for other types of weather.  Or you might want to show all the one-minute data points for the next 6 hours in a chart.  I only pulled the first and last epa_aqi values from the results. There are many other options available.  If you want a different type of data then change the “fields” input parameter. Choose any value from the <a href=“https://rapidapi.com/blog/api-glossary/parameters/”>Parameter</a> column in the <a href=“https://api.climacell.co/v3/api-docs/#/operations-tag-weather_data”><span data-offset-key=“dcm4n-1-0”>Weather Data section</span></a>.

This example uses something called a “Nowcast”. This returns predicted data points for each minute of the next 6 hours.  If you want an Hourly Forecast or Realtime data you can choose one of the other 2 endpoints.  The URL value (defined as $url in the example code) is what will change for different endpoints.

Once you are happy with what the widget will display, go to the Plugins page in the WordPress admin area. Click the Activate link for the Weather Widget Plugin to activate your plugin.
<h3>4. Use the WordPress Admin Area to place the widget on your site where you want it within your theme</h3>
Finally, go to the Appearance-> Widgets page in your WordPress admin area. Using this tool place your new widget wherever you want it to appear on your site.  If you don’t see your new Widget go to the plugins page to make sure it is activated.

<img class=“alignnone size-full wp-image-4289 aligncenter” src=“https://rapidapi.com/blog/wp-content/uploads/2020/04/Widget-Placement-in-WordPress.png” alt=“Widget Placement in WordPress” width=“441” height=“414” />

I put this one in my footer while developing it:

<img class=“alignnone size-full wp-image-4290” src=“https://rapidapi.com/blog/wp-content/uploads/2020/04/weather-widget-in-footer.png” alt=“Weather widget in footer” width=“1013” height=“130” />
<h2>Conclusion</h2>
In this tutorial, we walked through an example showing how to call an API from WordPress using a Plugin.  We added a widget with data populated from the <a href=“https://rapidapi.com/ClimaCell/api/climacell”>ClimaCell API</a>. That API contains a lot of weather details, we picked air quality to show. The data can be used for information or for advising future actions.  In this case, if I live in LA and want to run an errand I can check the air quality index to decide when to go.  😃

Bewertung: 4.7 - Stimmen: 48