How To Display Instagram Feed On Website Using PHP? Step By Step Guide!

Do you have a photo or video manager on your website? Do you upload photos or videos on your Instagram account?
If your answer is both YES, you’re wasting a lot of time managing your brand’s Instagram photos and videos online.
What if there’s a way to upload your photo or video ONCE, and then let if appear both on your Website and your Instagram account?
Will you be happy saving your precious time? Our code for today will make you happy then, just like we are!
Today we’re gonna talk about how to display publicly available Instagram photos and videos on your website using PHP and Instagram API.
This one is great if you want your Instagram photos and videos to be shown on your website in a synchronized way.

Once you uploaded a photo or video on Instagram, it will be automatically reflected and shown on your website too.

Today post will include the following contents:
1.0 Source Code Overview
2.0 Final Code Output
3.0 Get your Instagram Access Token
4.0 Create index.php File And Make It Bootstrap Ready
5.0 Add A Page Header
6.0 Initialize Variables Needed To Retrieve Instagram Feed
7.0 Get JSON Data And Decode It
8.0 Loop Through the JSON Data
9.0 Add Custom CSS
10.0 How To Display Non-Square Media?
11.0 Download the Complete Source Code
12.0 Social Media Scripts – LEVEL 3 – PRO PACK
13.0 Use the Instagram Feed Website Plugin
14.0 What’s Next?
15.0 Related Source Codes
16.0 Some Notes
 

1.0 SOURCE CODE OVERVIEW

Here’s an overview of what our code does:

1.1 Gets photos and videos from your Instagram account. (see more features on the LEVEL 2 live demo)

1.2 Display these instagram data to a webpage (assuming it is your PHP website.)

1.3 Show some awesome UI powered by Bootstrap. If you’re not yet familiar with this awesome front-end framework, see our step by step Bootstrap tutorial here.
 

2.0 FINAL CODE OUTPUT

2.1 LEVEL 1 Source Code Output

We have to know where we are going, once we completed the code tutorial below, we will achieve this output:

demo-screenshot-display-instagram-feed-level-1

2.2 LEVEL 2 Source Code Output

demo-screenshot-display-instagram-feed-PRO

2.3 LEVEL 3 Source Code Output

display-instagram-feed-on-website-level-3-demo

The LEVEL 3 live demo above shows codeofaninja’s Instagram posts from this link: http://instagram.com/codeofaninja

The LEVEL 2 and LEVEL 3 source codes has more features you might need. You can view the list of features and download them in section 11.2 and 11.3 below. For now, here’s the step by step tutorial of our LEVEL 1 source code. Enjoy!
 

3.0 GET YOUR INSTAGRAM ACCESS TOKEN

To get your Instagram API Access Token, use this Instagram access token generator.
 

4.0 CREATE INDEX.PHP FILE AND MAKE IT BOOTSTRAP READY

<!DOCTYPE html>
<html lang="en">
<head>
 
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 
    <title>Display Instagram Posts On Website - LEVEL 1 - Live Demo</title>
 
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
 
</head>
<body>
 
<div class="container">
<div class="row">
<!-- Instagram feed will be here --></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
 
<!-- [if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</body>
</html>

 

5.0 ADD A PAGE HEADER

This will be under the class=”col-lg-12″ div tag.

<div class="col-lg-12">
    <div class="page-header">
        <h1>Display Instagram Feed On Website - LEVEL 1 - Live Demo</h1>
    </div>
</div>

 

6.0 INITIALIZE VARIABLES NEEDED TO RETRIEVE INSTAGRAM FEED

This will be under page header.

<?php
// use this instagram access token generator http://instagram.pixelunion.net/ $access_token="CHANGE_TO_YOUR_ACCESS_TOKEN";
$photo_count=9;
$json_link="https://api.instagram.com/v1/users/self/media/recent/?";
$json_link.="access_token={$access_token}&count={$photo_count}"; 
?>

Let me explain the variables above:

  • $access_token will contain value retrieved from section 3.0
  • $photo_count is where you can specify how many posts you want to retrieve.
  • $json_link is where we’ll get the JSON data (photos and videos) of the Instagram user.

 

7.0 GET JSON DATA AND DECODE IT

Get the JSON data from the $json_link using json_decode() to decode it so we can loop through the contents later.

$json = file_get_contents($json_link);
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);

Use the following code instead if you’re using PHP version older than 5.4

$json = file_get_contents($json_link);
$obj = json_decode(preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $json), true);

I highly recommend you upgrade to PHP version 5.4+, you can ask you web hosting provider to do it for you.
 

8.0 LOOP THROUGH THE JSON DATA

Now we’ll loop through the JSON data retrieved from the $json_link, and also display the images using HTML.

foreach ($obj['data'] as $post) {
     
    $pic_text=$post['caption']['text'];
    $pic_link=$post['link'];
    $pic_like_count=$post['likes']['count'];
    $pic_comment_count=$post['comments']['count'];
    $pic_src=str_replace("http://", "https://", $post['images']['standard_resolution']['url']);
    $pic_created_time=date("F j, Y", $post['caption']['created_time']);
    $pic_created_time=date("F j, Y", strtotime($pic_created_time . " +1 days"));
    echo "<div class='col-md-4 col-sm-6 col-xs-12 item_box'>";        
        echo "<a href='{$pic_link}' target='_blank'>";
            echo "<img class='img-responsive photo-thumb' src='{$pic_src}' alt='{$pic_text}'>";
        echo "</a>";
        echo "<p>";
            echo "<p>";
                echo "<div style='color:#888;'>";
                    echo "<a href='{$pic_link}' target='_blank'>{$pic_created_time}</a>";
                echo "</div>";
            echo "</p>";
            echo "<p>{$pic_text}</p>";
        echo "</p>";
    echo "</div>";
}

 

9.0 ADD CUSTOM CSS

Add the following code below the bootstrap CSS in the head section.

.item_box{
    height:500px;
}
 
.photo-thumb{
    width:100%;
    height:auto;
    float:left; 
    border: thin solid #d1d1d1;
    margin:0 1em .5em 0;
    float:left; 
}

 

10.0 HOW TO DISPLAY NON-SQUARE MEDIA?

As of September 2015, Instagram API allows us to retrieve media (images and videos) in their original (non-square) aspect ratio.

The instructions above works for people who does not want to create an API client and prefer the square images. But for people who need the original aspect ratio of their media, you will need an API client access token. Here’s how to do it:

By the way, special thanks to @Ed in the comments section below for helping me figure it out.

10.1 Create an API Client

  1. Login to Instagram and go to https://instagram.com/developer/
  2. Click “Manage Clients”, then click “Register New Client”. Both located on the upper right corner for the page.
  3. Fill out the form. In the “Details” tab, make sure you fill out the “Application name” and “Valid redirect URIs”.
  4. In the “Security” tab, un-check “Disable implicit OAuth”
  5. Fill out all other required fields and click “Register”
  6. Once registered, it will give you a “Client ID”

10.2 How To Get Your API Client Access Token:

  1. Go to the following URL: https://www.instagram.com/oauth/authorize/?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=token
  2. Replace CLIENT_ID and REDIRECT_URL with your own and go to that URL.
  3. This will redirect you to your REDIRECT_URI.
  4. You will see your access token in your browser’s address bar. It looks like http://yourdomain.com/instagram_uri.php#access_token=xxx.yyy.zzz

10.3 How To Get Other User’s Access Token?

Other Instagram users, can use the same API client to get their access token.

  1. They need to receive a sandbox invite and accept it.
  2. They need to go to the same URL: https://www.instagram.com/oauth/authorize/?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=token
  3. They can see their access token in the browser’s address bar. It looks like http://yourdomain.com/instagram_uri.php#access_token=xxx.yyy.zzz

I probably need to build a simple tool for this. 😀

10.4 Check “Non Square Media”

You might still have to do the following:

  1. Locate your API Client and click “Edit”.
  2. Click the “Migrations” tab and check the box that says “Non square media”.
  3. Click “Update Client”.

instagram-get-non-square-media

Related from Instagram Blog: Thinking Outside the Square and API Migration.

Share this

Comment 1

Leave your question or feedback

따뜻한 말한마디가 블로거를 춤추게 합니다. 이메일 주소는 공개되지 않습니다.