Using Instagram’s API to Create an Image Gallery

  • follow us in feedly
Published July 6, 2013 by Brad Knutson
Create an Image Gallery with Instagram API

I’ve been taking a lot of Instagram photos lately, and it occurred to me that maybe I want to display a gallery of these images outside of the app. I realize that Instagram is accessible from desktop computers, but I want people to be able to see my images on my site, without being authenticated through Instagram.

So, to solve this problem, I dived into the Instagram API. It seems pretty straight forward, and I came up with a pretty cool example. I came up with an example that displays all my Instagram thumbnails and when you click on them, displays the large, original image in a jQuery lightbox.

Instagram Gallery Example

View Demo

Let’s dive into some code to see how I accomplished this.

PHP

First, let’s look at the PHP needed to make the API call and return the image paths. In order to accomplish this for yourself, you’ll need to retrieve your Instagram User ID and generate an Access Token. Directions can be found on Instagram’s Developer page on Authentication.

$userid = "USER-ID-GOES-HERE";
$accessToken = "ACCES-TOKEN-GOES-HERE";
$url = "https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch); 
$result = json_decode($result);

Essentially, all we’re doing is building our API call and using PHP’s CURL library to make our requests. The $result variable will store a JSON string with all the data we need.

HTML + PHP Variables

Now let’s build our page. Go ahead and style the page however you’d like, and choose a suitable jQuery (or otherwise) gallery/slider plugin.

<body>
<?php foreach ($result->data as $post): ?>
	<a class="fancybox" href="<?php echo $post->images->standard_resolution->url ?>" data-fancybox-group="gallery" title="<?php echo $post->caption->text ?>"><img src="<?php echo $post->images->thumbnail->url ?>" alt="<?php echo $post->caption->text ?>" /></a>
<?php endforeach ?>
</body>

That’s really all there is to it – not a lot going on. All we’re really doing here is looping through each object and pulling out the thumbnail URL, the large image URL, and the caption.

The images that are shown on the page will always be the most up-to-date images you have posted to your Instagram account. You could choose to cache the page, rather than making the API call every time the page loads – Instagram rate limits the number of API calls you can make to 5000/hour, so if you have a site that gets a lot of traffic caching may be a requirement.

Let me know what you think by leaving a comment below!

The following two tabs change content below.
Founder at Inbounderish
Brad Knutson is a Web Developer in the Twin Cities area of Minnesota. He has experience working with WordPress and Drupal, and also has an interest in SEO and Inbound Marketing.

Keep Up-to-Date

Subscribe

Topics

See a complete list of topics discussed in blog posts here.

Check These Out

Get 2 Weeks Free! Sign Up Today! Premium Managed WordPress Hosting Genesis Framework for WordPress SEO is complex. Tools should be simple. Thesis Theme for WordPress:  Options Galore and a Helpful Support Community

37 thoughts on “Using Instagram’s API to Create an Image Gallery

    1. Brad Knutson Post author

      You’ll need your Instagram user ID and then you’ll need to generate an access token. Once you have those, you’ll need to use this URL:

      If looks like you were trying to use your “client secret” which won’t work.

      Or, you could do this (and replace the variables in your PHP):

      Get your user ID here: http://jelled.com/instagram/lookup-user-id
      Get your access token here: http://jelled.com/instagram/access-token

  1. Ejjma

    Добрый день.
    Большое спасибо за такой полезный скрипт. Подскажите, пожалуйста, есть ли ограничения на вывод количества изображений – http://liashchanka.com/
    У меня выводиться только 18 штук

    (Translation)
    Good afternoon.
    Many thanks for such a useful script. Tell me, please, is there a limit on the number of output images – http://liashchanka.com/
    I only get 18 pieces

    Reply
    1. Brad Knutson Post author

      Perhaps your local version of XAMPP doesn’t have CURL enabled. That would be the first place I would look.

    2. Stefan

      Hi!

      I had the same problem as Nguyen. The instagram API uses “https://” which is the reason why the “curl_exec” command doesn’t return a result. I added the following line of code to the script right after the other “curl_setopt” commands. Now it works for me.

      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

      I hope that solves the problem for you as well.

  2. Alejandro

    Warning: Invalid argument supplied for foreach() in /home/medina/public_html/instagram_fancybox/index.php on line 40

    Whats wrong?.. my Server config?

    Reply
    1. Brad Knutson Post author

      I suspect the syntax for your foreach is incorrect. Can you paste your foreach statement here?

    2. Nguyen Duc Tho

      Dear Sir,
      Thanks for your help. B/c i run it at my localhost (xampp Server), it took error. But when i deploy on hosting it runs very well now. You are very kind and i’m great to know you.
      Have a nice day,
      Nguyen Duc Tho

  3. Jayson Pimentel

    data as $post): ?>
    <a class="fancybox" href="images->standard_resolution->url ?>” data-fancybox-group=”gallery” title=”caption->text ?>”><img src="images->thumbnail->url ?>” alt=”caption->text ?>” />

    sorry im really not into programming i cant seem to make it work.
    Also can i just paste this into wordpress or i have to add something?

    Reply
    1. Brad Knutson Post author

      Looks like your code snippet is missing some pieces. If you want to build this into WordPress, you’ll need to make a page template, you won’t be able to paste this right into a post. Also – if you use jQuery for the lightbox, then be careful about the $ symbol, as that will break your script. Good luck!

    2. Jayson Pimentel

      $userid = // unique user id goes here;
      $accessToken = // unique access token goes here;
      $url = “https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}”;
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_TIMEOUT, 20);
      $result = curl_exec($ch);
      curl_close($ch);
      $result = json_decode($result);

      foreach ($result->data as $post)
      {
      echo ‘ <a>images->standard_resolution->url.'” title=”‘.$post->caption->text.'”>images->thumbnail->url.'” alt=”SOME TEXT HERE”>';
      }

      here is my code, i dont need the fancy box i removed it. Cant i paste it on the homepage.

    3. Jayson Pimentel

      im looking for a something like this which i can populate a div because i want to combine this with gridrotator.js

  4. Rashminda

    Hi it’s a great tutorial.thanks for it.But sir I’m developing android app and I want to get images from Instagram.But I don’t know how to do it.sir please tell me step by step how to do that..Thank you sir.. :)

    Reply
    1. Brad Knutson Post author

      This tutorial will show you how to get your own images from Instagram – if you want to get other users, it gets much more complicated.

    2. Brad Knutson Post author

      I suggest you look through Instagram’s documentation: http://instagram.com/developer/. What you are trying to accomplish is pretty complicated, with involve authenticating your users with OAuth. There is nothing I can tell you that you can’t get from the Instagram documentation. Good luck!

  5. Zakaria KM

    Notice: Trying to get property of non-object in C:\wamp\www\instagram\index.php on line 17

    Warning: Invalid argument supplied for foreach() in C:\wamp\www\instagram\index.php on line 17

    Have no idea what is happening :-/

    Reply
    1. RicM

      Hi Brad, I am also having the same issue as Zakaria KM. My script returns the error “Invalid argument supplied for foreach…”
      I have used the foreach copied directly from your example. Is there anything else that needs to be changed?

      Thanks in advance for your help

  6. Hazel Evans

    Hi,

    Lovely post!

    I’m really looking for some help in displaying more than 20 images but the link above you suggested seems broken? I wonder if you might have any other recomendations?

    Best,

    Hazel

    Reply

Share Your Thoughts

Your email address will not be shown.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">