APIs can help you to add functionality to your WordPress plugins and themes. In this tutorial I will show you how to use any API (whether it be from Flickr, Google, Twitter, and so on) with WordPress. You will learn how to connect, collect data, store and render–everything you need to know to extend your plugin or theme with new functionality!
We will use Flickr as an example, creating a simple
widget that displays the latest Flickr images in order of username.
Wait, What’s an API?
“API” stands for Application Programming Interface; an intermediary between applications, allowing them to communicate, sending information back and forth in real time. We’ll be using a Web API, one which uses HTTP to fetch data from a remote location on the internet somewhere.
“APIs are used by software applications in much the same way that interfaces for apps and other software are used by humans.” – David Berlind, ProgrammableWeb
If you want to get an even clearer idea of what APIs are before we dive into our tutorial, here are some more resources to help you:
NewsThe Increasing Importance of APIs in Web Development
WordPressUse the WooCommerce API to Customize Your Online Store
API WordPress Plugins on Envato Market
If you’d like to see what other WordPress developers are building with APIs, check out this collection of plugins on Envato Market–plenty of API goodness to get stuck into!
1. Organize Your Working Environment
Let’s begin by organizing our
working environment. Start by downloading the Postman
app, which provides an API development environment that makes it easy to connect,
test, and develop any API. For individuals and small teams it’s completely free.
We’re going to build a widget in a simple WordPress plugin, so
make sure you have WordPress installed.
2. Code the Plugin Basics
To start let’s create a simple plugin called flickr-widget.
Create a folder with that name and create a flickr-widget.php file in
it. At the top of the file place the following code (feel free to change the Author and URIs with your own details):
/* Plugin Name: Flickr widget Plugin URI: https://www.enovathemes.com Description: Display recent Flickr images Author: Enovathemes Version: 1.0 Author URI: http://enovathemes.com */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
Note: this is rudimentary plugin, so I won’t load a language file
or create any additional parameters.
Put the freshly created plugin folder inside your WordPress install: wp-content > plugins. You can now activate it from within the WordPress admin dashboard > plugins.
You won’t see any changes to your WordPress because we haven’t actually added any functional code.
A Note on Using APIs
Before we go any further, let me quickly mention API use. Any service whose API you want to use will have documentation; I
highly recommend you look closely at it. You can use APIs with all kinds of development languages and often get data back in any format you need: PHP, JSON, Java etc. Good documentation will contain detailed information on how to connect to the API, with instructions for
each language, and also the main API endpoints (an endpoint is one end of a
Web APIs are typically categorized as being either SOAP or REST. SOAP relies solely on XML to provide
messaging services, while REST offers a more lightweight method, using URLs in
most cases to receive or send information. In our example we will use a REST API.
3. Configure and Test API with Postman
So, here is our plan:
- Configure and test API with Postman
- Connect, collect, and format data from Flickr REST
- Cache the data with WordPress transients
Let’s refer to the Flickr API documentation. Under the Request Formats section you have REST, XML-RPC, SOAP. We need the REST. Click it and you will see an example of a general Flickr REST API Endpoint:
With the Flickr REST
API we can GET, POST, and DELETE any Flickr data we want. Copy the sample
endpoint and paste it into Postman (make sure your request type is set to GET).
Click the Send button and… error!
The sample request included the compulsory Flickr API method, but we didn’t specify the API key that is required in order to connect (keys are used to track and control how an API is being
used, for example to prevent malicious use or abuse of the API as defined
perhaps by terms of service).
4. Get API Key
Having established that we need an API key, let’s go and get one. In order to create one you will first need to
have a Flickr/Yahoo account. Once you’ve entered the API dashboard
click on the link create your first:
After that click on the Request an API Key.
Many API providers have their own specific terms on API usage. Some limit
access, others have light and pro versions, or commercial and non-commercial. Sometimes
API keys are provided after manual approval; it depends entirely on the API provider. I have
chosen Flickr, because it has simple API requirements. For example, Twitter
requires a detailed description of the app you want to build before providing an
API key, and this is then reviewed by the review team.
That said, click on the Apply for a
non-commercial key button and provide some basic info on the app name.
Once you’ve submitted the request you will get the API key (which identifies you) and secret code (which proves you are who you say you are) immediately. Keep these details safe!
5. Set the Request Parameters
Now we will need a method to request data. From the Flickr API
documentation we can see that Flickr has tons to choose from. Some methods, like
image posting, or deleting, require authentication. Flickr uses OAuth for this; an open, simple, and secure
protocol that enables applications to authenticate users and interact with API
providers on their behalf. The end user’s information is securely transferred
without revealing the identity of the user.
For now, we’ll use simple methods that don’t require oAuth. Click on flickr.photos.getRecent method to see what’s required. This method does not need authentication, but it does take several
arguments: api_key (required), extras, per_page, page. Let’s make a simple request in Postman using our parameters:
- API general endpoint – https://flickr.com/services/rest
- API key – f49df4a290d8f224ecd56536af51FF77 (this
is a sample API key which you’ll need to replace with your own)
- Method – flickr.photos.getRecent
It will look like this:
This will return the list of recent public images from Flickr in
I always set data format to
auto to let Postman decide what format the data is. With Postman you have several data format options: JSON (my favorite), XML, HTML and Text. Flickr returns data in XML format, but this is not a problem for us, as we can add an additional parameter to get data in JSON
6. Connect, Collect, and Format Data
Now we know how to request data using the REST API, let’s build our WordPress Flickr widget. In the plugin’s main PHP file paste the widget code. I won’t cover
the specifics of WordPress widget creation in this tutorial as our focus is different. We have a learning guide Introduction to Creating Your First WordPress Widget by Rachel McCollin which should get you up to speed if you need it.
In the WordPress admin navigate to Appearance > Widgets and add
the “Photos from Flickr” widget to a widget area. Now if you go to the front-end you will see the widget title, but no results just yet.
Back in our plugin PHP file, here we render the widget output itself. We have our API key, and the method, and the format we’re looking for. Now we will need to make sure the Flickr user id is provided, and the number of photos the user wants to fetch. These are are gathered from the widget settings.
Note: to get a Flickr
user id use this service. I
am using envato as the username, and the id is 52617155@N08. Enter the following
code inside IF statement:
$url = 'https://www.flickr.com/services/rest/'; $arguments = array( 'api_key' => 'f49df4a290d8f224ecd56536af51FF77', 'method' => 'flickr.people.getPublicPhotos', 'format' => 'json', 'user_id' => $user_id, 'per_page'=> $photos_number, ); $url_parameters = array(); foreach ($arguments as $key => $value) $url_parameters = $key.'='.$value; $url = $url.implode('&', $url_parameters);
At this point we can knit together the final REST API endpoint url with all the
arguments we’ve collected.
Now we’ll make an API request with the
file_get_contents() php function:
$response = file_get_contents($url); if ($response) print_r($response);
If you now go to the front-end you will something like this outputted:
jsonFlickrApi("photos":"page":1,"pages":1033,"perpage":1,"total":"1033","photo":["id":"15647274066","owner":"52617155@N08","secret":"2ee48c3fe9","server":"3940","farm":4,"title":"Halloween 2014 at Envato in Melbourne","ispublic":1,"isfriend":0,"isfamily":0],"stat":"ok")
Our request was successful and returned useful data, so now let’s decode and format
it. We’ll begin by cleaning up the JSON string–first by removing the wrapper (
jsonFlickrApi(...);) with a
str_replace. Then we’ll decode the JSON url:
$response = str_replace('jsonFlickrApi(', "http://webdesign.tutsplus.com/", $response); $response = str_replace('})', '}', $response); $response = json_decode($response,true);
Now if we print our results we will see an associative array with data. When we’re ready we can loop through that array and create the data output structure. But first, take a closer look at the small parameter
stat. According to the Flickr documentation this indicates the response status. So, before creating the structure of the widget let’s use this status to make sure we have the correct data. Add an IF statement:
if ($response['stat'] == 'ok') // code here…
Create an empty array before the IF statement. This array will then be used to contain the
$response_results = array();
foreach loop should now look like this:
if ($response['stat'] == 'ok') foreach ($response['photos']['photo'] as $photo) $response_results[$photo['id']]['link'] = esc_url('//flickr.com/photos/'.$photo["owner"].'/'.$photo["id"]); $response_results[$photo['id']]['url'] = esc_url('//farm'.$photo["farm"].'.staticflickr.com/'.$photo["server"].'/'.$photo["id"].'_'.$photo["secret"].'_s.jpg'); $response_results[$photo['id']]['alt'] = esc_attr($photo["title"]);
loop through each photo object in the photos array from our response data. Our widget
needs the following information to function properly:
- Image absolute URL
- Image link to Flickr
- Image description/alt text
Examine this page and you
will understand why I used the given structure. Here you will find the detailed
information on how to create the image path and image link.
Create Widget Output
$response_results array contains the exact data we need to create our widget:
if (!empty($response_results)) $output = "http://webdesign.tutsplus.com/"; $output .= '<ul class="widget-flickr-list">'; foreach ($response_results as $photo) $output .= '<li>'; $output .= '<a href="http://webdesign.tutsplus.com/".$photo['link']."http://webdesign.tutsplus.com/" target="_blank">'; $output .= '<img src="http://webdesign.tutsplus.com/".$photo['url']."http://webdesign.tutsplus.com/" alt="http://webdesign.tutsplus.com/".$photo['alt']."http://webdesign.tutsplus.com/" />'; $output .= '</a>'; $output .= '</li>'; $output .= '</ul>'; echo $output;
We begin by making sure our response is not
empty. After that we create an unordered list, storing it in
$output, then loop through each image, adding a wrapper link, all the other details, and finally outputting the whole thing with
If you now go to the site
front-end you will see a list of images!
Let’s add some basic styling with CSS to make it look better.
Create an empty flickr-widget.css
file in the root plugin folder. In the top of the plugin file paste the following
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly function register_script() wp_register_style('widget-flickr', plugins_url('/widget-flickr.css', __FILE__ )); add_action( 'wp_enqueue_scripts', 'register_script' );
Then, inside the IF statement at the very top add the
Inside the css file add basic styling:
.widget-flickr-list list-style: none; margin:0 -4px 0 -4px; padding: 0; .widget-flickr-list:after content: "http://webdesign.tutsplus.com/"; clear: both; .widget-flickr-list li display: block; float: left; width: 25%; margin:0; padding: 4px;
Now it looks much better!
Bonus: Cache the Data with WordPress Transients
At this stage we’ve finished the widget, but there is
one more little thing that will take our development to the next level:
Any API request uses your site’s resources and increases load time. Each browser reload will send an API request, which could be multiple users at the same time. What
if for some reason your API provider host is down? Your site will suffer load
difficulties. The solution is
to cache the results and update at a give time interval. So the first time a user
visits our page the API request will be sent, but the next time, or with another user, we won’t need to send an API request but instead fetch the results from our site cache.
Let’s modify the widget code to
if (!empty($flickr_id)) $api_key = 'f49df4a290d8f224ecd56536af51FF77'; $transient_prefix = esc_attr($flickr_id . $api_key); if (false === ($response_results = get_transient('flickr-widget-' . $transient_prefix))) $url = 'https://www.flickr.com/services/rest/'; $arguments = array( 'api_key' => $api_key, 'method' => 'flickr.people.getPublicPhotos', 'format' => 'json', 'user_id' => $flickr_id, 'per_page' => $photos_number, ); $url_parameters = array(); foreach ($arguments as $key => $value) $url_parameters = $key . '=' . $value; $url .= '?' . implode('&', $url_parameters); $response = file_get_contents($url); if ($response) $response = str_replace('jsonFlickrApi(', "http://webdesign.tutsplus.com/", $response); $response = str_replace(')', '', $response); $response = json_decode($response, true); $response_results = array(); if ($response['stat'] == 'ok') foreach ($response['photos']['photo'] as $photo) $response_results[$photo['id']]['link'] = esc_url('//flickr.com/photos/' . $photo["owner"] . '/' . $photo["id"]); $response_results[$photo['id']]['url'] = esc_url('//farm' . $photo["farm"] . '.staticflickr.com/' . $photo["server"] . '/' . $photo["id"] . '_' . $photo["secret"] . '_s.jpg'); $response_results[$photo['id']]['alt'] = esc_attr($photo["title"]); if (!empty($response_results)) $response_results = base64_encode(serialize($response_results)); set_transient('flickr-widget-' . $transient_prefix, $response_results, apply_filters('null_flickr_cache_time', HOUR_IN_SECONDS * 2)); else return new WP_Error('flickr_error', esc_html__('Could not get data', 'your-text-domain')); if (!empty($response_results)) $response_results = unserialize(base64_decode($response_results)); wp_enqueue_style('widget-flickr'); $output = "http://webdesign.tutsplus.com/"; $output .= '<ul class="widget-flickr-list">'; foreach ($response_results as $photo) $output .= '<li>'; $output .= '<a href="http://webdesign.tutsplus.com/" . $photo['link'] . "http://webdesign.tutsplus.com/" target="_blank">'; $output .= '<img src="http://webdesign.tutsplus.com/" . $photo['url'] . "http://webdesign.tutsplus.com/" alt="http://webdesign.tutsplus.com/" . $photo['alt'] . "http://webdesign.tutsplus.com/" />'; $output .= '</a>'; $output .= '</li>'; $output .= '</ul>'; echo $output; }
I won’t describe what the
transient is and how it works, just what it does. Any time the widget
is rendered we first check if the transient is in place; if it is present we
fetch results from transient, but if not, we make an API request. And each two hours our transient expires, in order to keep our latest Flickr images actual and up
With the WordPress plugin Transients Manager you can even see what your cached Flickr API request
results look like:
And the final touch here is to
remove transient for every widget update. For example, if you want to change the number
of images displayed, or change the username, you’d need to make a new API request. This can be done with the
WordPress filter, or the widget class public function update:
public function update($new_instance, $old_instance) $instance = $old_instance; $instance['title'] = strip_tags($new_instance['title']); $instance['photos_number'] = strip_tags($new_instance['photos_number']); $instance['flickr_id'] = strip_tags($new_instance['flickr_id']); $api_key = 'f49df4a290d8f224ecd56536af51FF77'; $transient_name = 'flickr-widget-' . esc_attr($instance['flickr_id'] . $api_key); delete_transient($transient_name); return $instance;
That was a lot of effort, but now you know how to work with WordPress and APIs! If you enjoyed this post and would like to see additional tutorials on APIs or transients, let me know in
the comments section.
To grab the widget sample files head over to the GitHub repository.