How to Integrate an External API in WordPress
How do you call an API from WordPress? A great way to do that is by using a Plugin (or directly in a page). 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 W3Techs.
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 call APIs – 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 create a plugin. 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 ClimaCell Weather API and it includes air quality as one of its available parameters.
TL;DR: How to Call a 3rd Party API in WordPress
- Get an API Key for an API
- Create a Plugin to add a widget
- Customize your Plugin with API
- Use the WordPress Admin to add the widget
Prerequisites to call an API from WordPress
Before following the steps below you’ll need the following:
- A WordPress Site
- A RapidAPI account
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 Rapidapi.com.
Here are the main steps we will follow to integrate an API with WordPress through a Plugin:
- Get an API key for the API
- Create a Plugin for adding a widget to your WordPress site
- Customize your plugin with your API key and specific information you want to display in the widget
- Use the WordPress Admin Area to place the widget on your site where you want it within your theme
Now let’s go through the steps in more detail:
1. Get an API key for the API
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:
In order to get an API Key for the ClimaCell API, go to the ClimaCell pricing page and click on one of the blue Select Plan buttons. Then go to the ClimaCell Endpoints page and you will see your X-RapidAPI-Key populated in the Header Parameters section of the API test area.
2. Create a Plugin for adding a widget to your WordPress site
Next, you can use some sample code to create a new plugin for WordPress. To do that, follow these steps:
- Save the following code in a file called weather-widget-plugin.php
- Place the PHP file into a folder called weather-widget-plugin.
- Once you have the file in that folder, compress the folder into a file called weather-widget-plugin.zip.
- 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.
Plugin file weather-widget-plugin.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' => __( '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&lat=34.0201598&lon=-118.692597"; curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => 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 = "<strong>".$responseObj[0]->epa_aqi->value."</strong>"; $firstTime = date("Y-m-d H:i:s T",strtotime($responseObj[0]->observation_time->value)); $numResults = count($responseObj); $lastEPAAQI = "<strong>".$responseObj[$numResults-1]->epa_aqi->value."</strong>"; $lastTime = date("Y-m-d H:i:s T",strtotime($responseObj[$numResults-1]->observation_time->value)); //This is the content that gets populated into the widget on your site echo "The <a href='https://www.airnow.gov/index.cfm?action=aqibasics.aqi'>air quality EPA score</a> ". "is currently $firstEPAAQI at $firstTime and is forecasted to be $lastEPAAQI at $lastTime <br>"; } 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 ?>
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:
This is how the interface will look after uploading the plugin:
Before you click the Activate Plugin button, you’ll need to modify the plugin to meet your needs.
3. Customize your plugin with your API key and specific information you want to display in the widget
First, you’ll need to replace the Xs in the code with your RapidAPI key 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 Filezilla 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 google maps 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 URL 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 Parameter column in the Weather Data section.
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.
4. Use the WordPress Admin Area to place the widget on your site where you want it within your theme
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.
I put this one in my footer while developing it:
Conclusion
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 ClimaCell API. 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. 🙂
NaGG says
Good article. Can we integrate other APIs as a page instead of widget?
Let’s say I have one API, which will give breweries locations based on search query( location) entered by user.
Robert Davis says
Thank you. Stay tuned, I’ll be writing an article about integrating an API into WordPress as a page next. 🙂
Robert Davis says
If you want to integrate an API as a page please see this link for directions: https://rapidapi.com/blog/integrate-external-api-wordpress/
JM says
I love this tutorial, made using Rapid Api with WordPRess so easy, I guess one way also to use as a page would be to create the shortcode and display where you want. I do have a question though, how can I call the lat/long from an existing field already from that page using widget or shortcode?
Robert Davis says
Hi JM, thanks for the comment. Populating the lat/long from an existing field really depends on where the data is stored and in what context you are looking for it. The lat/long for the middle of LA are hardcoded in this example in the plugin code itself (line 44). So if you have a variable available in the context of the weather_widget class, you can use that in the URL string on line 44 of the plugin code above. It will likely be 2 variables, one for latitude and one for longitude.
Regards,
Robert
Shanmuganathan says
Thank You for this article, Can we integrate API as Search and get result example, search by post code and search by post code to get post office name
Robert Davis says
Hi Shanmuganathan,
In order to integrate and API as a search and display the results you could replace the widget contents on line 80 of the example class above. Instead of immediately showing the results there you could show a form. But in order to show the results without going to a new page you’d need to use an ajax call and then populate the results on the page somewhere using JavaScript. That could be a topic for a whole separate article…
Regards,
Robert
Vijay says
Hi, great tutorial. I have a real estate WordPress website. And one of the agency have given me a external api to intrgrate to acquire the leads generated after the form is submitted from his property listed. So will the custom plugin or template work for this property type too?
Robert Davis says
Hi Vijay,
Yes you could use a custom plugin to call the external leads api you are describing. In that case I expect you would then want to save the results in your local database instead of showing them on the page. 🙂
Regards,
Robert
Nikhil Joy says
Very good article. Clearly understandable. It helped me so much.
Below is a task given for me as a machine test. I failed to do it as I am a beginner of API.
A client wants to have a plugin that will allow them automatically publish a custom post type “todos” from a todo api.
The plugin needs to
Register the CPT
Register a settings page
Add Setting for API endpoint – https://jsonplaceholder.typicode.com/todos
Add a button to manually call an admin Ajax action to get the todos and publish them.
Add a section to show progress of the todos being added
The plugin should not add TODOS that already exists.
The plugin should allow the new todos to be viewed on the frontend.
Can you please give an idea of doing this.
Robert Davis says
Hi Nikhil,
It sounds to me like you could use a good foundation. I would recommend taking a course like the one at https://www.udemy.com/course/create-wordpress-plugins/ to get you started.
Regards,
Robert
James Kelly says
Hi Robert
Thanks for this great article. Is it possible to use this or another template widget plugin for any API? And if so do you know where I could find one?
Or if parts can be used as a generic template can you advise which parts that would be?
Many thanks
James
Robert Davis says
Hi James,
Yes you could use this as a template widget plugin for another API if you’d like. You’d want to change the class and function names to match whatever API you are using, and change the API integration to match your API. If you stay within the RapidAPI library of APIs that will reduce the amount of changes you’ll need to make as they have a standard interface.
Regards,
Robert
Sean Lumaye says
Hello Robert,
I work for a transit company and was given an API by a third party software that we use to book our charter trips on. However, I have very little experience working on websites in general. Where would you point me to learn the basics of adding an API. I am absolutely stumped.
Robert Davis says
Hi Sean,
If I were in your position I would ask the company who gave you the API to provide a reference to at least one example interface which uses the API. If you will be integrating the API into your own website you’ll need some documentation from them about how the API works and what requirements it has. If you want to understand APIs better in general you can take a look at https://rapidapi.com/blog/how-to-use-an-api/.
Regards,
Robert
Pat says
Thanks for that tutorial!
I tried it unfortunately nothing shows on my website, even no error, weird isn’t it?
Robert Davis says
Hi Pat,
You could try some of the suggestions at https://www.wpbeginner.com/wp-tutorials/how-to-fix-the-wordpress-white-screen-of-death/ to help you troubleshoot your blank page.
Regards,
Robert
ronny says
hi,
I want to use rapid news API’s to automatically post news articles to my WordPress website how can I do that
Robert Davis says
Hi Ronny,
In order to automatically post articles to your wordpress site you could to automate the following steps:
1) Download desired news links retrieved from a rapidapi news api like https://rapidapi.com/newscatcher-api-newscatcher-api-default/api/google-news/. The results contain links to news articles, not the full content.
2) Create a widget like the one in this article to show a news article within an iframe that uses an article link for the contents.
3) OR create a new custom page template which shows multiple news articles in separate iframes. This could work similar to the method I described at https://rapidapi.com/blog/integrate-external-api-wordpress/.
Regards,
Robert
Pihu Sen says
Hello
I tried to install the plugin shown in this article but it could not be installed. It says that the plugin contains no file. What should I do?
Robert Davis says
Did you make sure the zip file you are uploading contains weather-widget-plugin.php?
Sean says
Hi Robert,
Epic work on putting these wordpress API examples together! I’d be very interested in seeing an example where form data is used to make a (GET) request to an API so that the user can receive a personalised response. Using AJAX I suppose. Imagine a web based calculator of sorts which offloads compute to an external server by passing form input to an API, then displaying the response in the form of key figures, a table or a graph.
Loving your work 🙂
Cheers,
Sean
Robert Davis says
Hi Sean,
Thanks for your encouragement! Which API at https://rapidapi.com/hub would you want to see an integration with through AJAX in a WordPress context?
Regards,
Robert
Chinedum says
Hey Robert,
nice article! Could you please drop your Instagram handle or phone number so that I can reach you.
I need personal guidance from an expert. I am working on a website(wordPress website) at the moment and I am clueless as to how to go about writing the code that will run certain things at the backend.
Robert Davis says
I’m not available for personal consulting at this time, but there are many great tutorials and examples on this site and others like it.