Advertisement
  1. Web Design
  2. WordPress Plugins

How to Incorporate External APIs in Your WordPress Theme or Plugin

Scroll to top
Read Time: 13 min

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:

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!

api wordpress plugins on codecanyonapi wordpress plugins on codecanyonapi wordpress plugins on codecanyon
API WordPress plugins on Envato Market

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.

postman apppostman apppostman app

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):

1
/*

2
    Plugin Name: Flickr widget

3
    Plugin URI: https://www.enovathemes.com

4
    Description: Display recent Flickr images

5
    Author: Enovathemes

6
    Version: 1.0

7
    Author URI: http://enovathemes.com

8
*/
9
10
if ( ! defined( 'ABSPATH' ) ) {
11
    exit; // Exit if accessed directly

12
}

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 communication channel).

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 API
  • 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: https://www.flickr.com/services/rest/.

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! 

postman errorpostman errorpostman 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.

app detailsapp detailsapp details

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:

1
https://www.flickr.com/services/rest/?api_key=f49df4a290d8f224ecd56536af51FF77&method=flickr.photos.getRecent

This will return the list of recent public images from Flickr in XML format. 

XML formatXML formatXML format
XML format

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 &format=json:

JSON formatJSON formatJSON format
JSON format

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:

1
$url = 'https://www.flickr.com/services/rest/';
2
$arguments = array(
3
    'api_key' => 'f49df4a290d8f224ecd56536af51FF77',
4
    'method'  => 'flickr.people.getPublicPhotos',
5
    'format'  => 'json',
6
    'user_id' => $user_id,
7
    'per_page'=> $photos_number,
8
);
9
$url_parameters = array();
10
foreach ($arguments as $key => $value){
11
    $url_parameters[] = $key.'='.$value;
12
}
13
$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:

1
$response = file_get_contents($url);
2
if ($response) {
3
    print_r($response);
4
}

If you now go to the front-end you will something like this outputted:

1
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:

1
$response = str_replace('jsonFlickrApi(', '', $response);
2
$response = str_replace('})', '}', $response);
3
$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: 

1
if ($response['stat'] == 'ok') {
2
    // code here…

3
}

Create an empty array before the IF statement. This array will then be used to contain the collected data:

1
$response_results = array();

Your foreach loop should now look like this:

1
if ($response['stat'] == 'ok') {
2
    foreach ($response['photos']['photo'] as $photo) {
3
        $response_results[$photo['id']]['link'] = esc_url('//flickr.com/photos/'.$photo["owner"].'/'.$photo["id"]);
4
        $response_results[$photo['id']]['url']  = esc_url('//farm'.$photo["farm"].'.staticflickr.com/'.$photo["server"].'/'.$photo["id"].'_'.$photo["secret"].'_s.jpg');
5
        $response_results[$photo['id']]['alt']  = esc_attr($photo["title"]);
6
    }
7
}

Here we 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

Now our $response_results array contains the exact data we need to create our widget:

1
if (!empty($response_results)) {
2
    $output = '';
3
    $output .= '<ul class="widget-flickr-list">';
4
        foreach ($response_results as $photo) {
5
            $output .= '<li>';
6
                $output .= '<a href="'.$photo['link'].'" target="_blank">';
7
                    $output .= '<img src="'.$photo['url'].'" alt="'.$photo['alt'].'" />';
8
                $output .= '</a>';
9
            $output .= '</li>';
10
        }
11
    $output .= '</ul>';
12
    echo $output;
13
}

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 echo;.

If you now go to the site front-end you will see a list of images! 

Flickr imagesFlickr imagesFlickr 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 code:

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

3
}
4
function register_script(){
5
wp_register_style('widget-flickr', plugins_url('/widget-flickr.css', __FILE__ ));
6
}
7
add_action( 'wp_enqueue_scripts', 'register_script' );

Then, inside the IF statement at the very top add the code:

1
if (!empty($response_results)) {
2
wp_enqueue_style('widget-flickr');

Inside the css file add basic styling:

1
.widget-flickr-list {
2
    list-style: none;
3
	margin:0 -4px 0 -4px;
4
	padding: 0;
5
}
6
7
.widget-flickr-list:after {
8
	content: "";
9
	clear: both;
10
}
11
12
.widget-flickr-list li {
13
	display: block;
14
	float: left;
15
	width: 25%;
16
	margin:0;
17
	padding: 4px;
18
}

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: caching. 

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 cache results:

1
if (!empty($flickr_id))
2
{
3
4
    $api_key = 'f49df4a290d8f224ecd56536af51FF77';
5
6
    $transient_prefix = esc_attr($flickr_id . $api_key);
7
8
    if (false === ($response_results = get_transient('flickr-widget-' . $transient_prefix)))
9
    {
10
11
        $url = 'https://www.flickr.com/services/rest/';
12
13
        $arguments = array(
14
            'api_key' => $api_key,
15
            'method' => 'flickr.people.getPublicPhotos',
16
            'format' => 'json',
17
            'user_id' => $flickr_id,
18
            'per_page' => $photos_number,
19
        );
20
21
        $url_parameters = array();
22
        foreach ($arguments as $key => $value)
23
        {
24
            $url_parameters[] = $key . '=' . $value;
25
        }
26
27
        $url .= '?' . implode('&', $url_parameters);
28
29
        $response = file_get_contents($url);
30
31
        if ($response)
32
        {
33
34
            $response = str_replace('jsonFlickrApi(', '', $response);
35
            $response = str_replace('})', '}', $response);
36
            $response = json_decode($response, true);
37
38
            $response_results = array();
39
40
            if ($response['stat'] == 'ok')
41
            {
42
                foreach ($response['photos']['photo'] as $photo)
43
                {
44
                    $response_results[$photo['id']]['link'] = esc_url('//flickr.com/photos/' . $photo["owner"] . '/' . $photo["id"]);
45
                    $response_results[$photo['id']]['url'] = esc_url('//farm' . $photo["farm"] . '.staticflickr.com/' . $photo["server"] . '/' . $photo["id"] . '_' . $photo["secret"] . '_s.jpg');
46
                    $response_results[$photo['id']]['alt'] = esc_attr($photo["title"]);
47
                }
48
49
                if (!empty($response_results))
50
                {
51
                    $response_results = base64_encode(serialize($response_results));
52
                    set_transient('flickr-widget-' . $transient_prefix, $response_results, apply_filters('null_flickr_cache_time', HOUR_IN_SECONDS * 2));
53
                }
54
55
            }
56
57
        }
58
        else
59
        {
60
            return new WP_Error('flickr_error', esc_html__('Could not get data', 'your-text-domain'));
61
        }
62
63
    }
64
65
    if (!empty($response_results))
66
    {
67
        $response_results = unserialize(base64_decode($response_results));
68
        wp_enqueue_style('widget-flickr');
69
        $output = '';
70
        $output .= '<ul class="widget-flickr-list">';
71
        foreach ($response_results as $photo)
72
        {
73
            $output .= '<li>';
74
            $output .= '<a href="' . $photo['link'] . '" target="_blank">';
75
            $output .= '<img src="' . $photo['url'] . '" alt="' . $photo['alt'] . '" />';
76
            $output .= '</a>';
77
            $output .= '</li>';
78
        }
79
        $output .= '</ul>';
80
        echo $output;
81
    }
82
}

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 to date. 

With the WordPress plugin Transients Manager you can even see what your cached Flickr API request results look like:

Transients Manager pluginTransients Manager pluginTransients Manager plugin

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 widget_update_callback WordPress filter, or the widget class public function update:

1
public function update($new_instance, $old_instance)
2
{
3
    $instance = $old_instance;
4
    $instance['title'] = strip_tags($new_instance['title']);
5
    $instance['photos_number'] = strip_tags($new_instance['photos_number']);
6
    $instance['flickr_id'] = strip_tags($new_instance['flickr_id']);
7
8
    $api_key = 'f49df4a290d8f224ecd56536af51FF77';
9
    $transient_name = 'flickr-widget-' . esc_attr($instance['flickr_id'] . $api_key);
10
11
    delete_transient($transient_name);
12
13
    return $instance;
14
}

Conclusion

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.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.