How to display Instagram Feed on your website using PHP?

display-instagram-feed-website

In this tutorial, I will show you how to display Instagram feed on website using PHP.

Photos and videos from your Instagram account are not shown to your website visitors. You spend a lot of time creating, editing, and managing your photos and videos. But your fans, audience, and customers from your website still do not see your Instagram photos and videos.

Our code in this tutorial will allow you to automatically display your Instagram feed on your website using PHP. Create and edit your photos and videos on Instagram and any changes will also be reflected on your website.

We will use the official Instagram Basic Display API. This API allows users to read basic profile information, photos, videos, and albums of the connected account.

Display Instagram feed on website using PHP

Here are the steps to display Instagram feed on website using PHP.

  1. Retrieve long-lived access token.
  2. Use our PHP code to display your Instagram feed.
  3. Use our CSS code to make the display look good.
  4. View our output.

Retrieve your long-lived access token

The long-lived access token is like a key that you will use to programmatically retrieve your Instagram photos and videos. You will use this token on our PHP code later.

  1. Create a Facebook developer account. Create your Facebook developer account here. Then, you also need to create a Facebook application here.
  2. Configure Instagram’s basic display API. Instagram’s documentation is good enough and I don’t want to repeat the same instructions here. Follow the guide here.
  3. Get your long-lived access token. By default, Instagram API will give you a short-lived access token that is valid only for 24 hours. If you get your long-lived access token, it will be valid for 60 days. Learn how to get a valid long-lived access token here.

Use our PHP code to display your Instagram feed

Once you got your long-lived access token, use it as the value of the $token variable below. The code below will allow you to display the list of posts

<?php 
// query the user media
$fields = "id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username";
$token = "your_long_lived_user_access_token";
$limit = 10;

$json_feed_url="https://graph.instagram.com/me/media?fields={$fields}&access_token={$token}&limit={$limit}";
$json_feed = @file_get_contents($json_feed_url);
$contents = json_decode($json_feed, true, 512, JSON_BIGINT_AS_STRING);

echo "<div class='ig_feed_container'>";
    foreach($contents["data"] as $post){
        
        $username = isset($post["username"]) ? $post["username"] : "";
        $caption = isset($post["caption"]) ? $post["caption"] : "";
        $media_url = isset($post["media_url"]) ? $post["media_url"] : "";
        $permalink = isset($post["permalink"]) ? $post["permalink"] : "";
        $media_type = isset($post["media_type"]) ? $post["media_type"] : "";
        
        echo "
            <div class='ig_post_container'>
                <div>";

                    if($media_type=="VIDEO"){
                        echo "<video controls style='width:100%; display: block !important;'>
                            <source src='{$media_url}' type='video/mp4'>
                            Your browser does not support the video tag.
                        </video>";
                    }

                    else{
                        echo "<img src='{$media_url}' />";
                    }
                
                echo "</div>
                <div class='ig_post_details'>
                    <div>
                        <strong>@{$username}</strong> {$caption}
                    </div>
                    <div class='ig_view_link'>
                        <a href='{$permalink}' target='_blank'>View on Instagram</a>
                    </div>
                </div>
            </div>
        ";
    }
echo "</div>"
?>

Use our CSS code to make the display look good

Here’s the CSS code I used with the code above.

.ig_feed_container{
    width:100%; margin:0 auto; font-family:Arial, Helvetica, sans-serif;
}

.ig_post_container{
    border: 2px solid #f1f1f1; margin-bottom:25px; margin-left:3%; width:20%; height:550px; float:left;
}

.ig_post_container img{
    width:100%;
}

.ig_post_container .ig_post_details{
    padding:15px;
}

.ig_post_container .ig_view_link{
    margin-top:10px;
}

View our output

The output will look like the following.

Display Instagram feed using a website plugin

If you do not want to code, use a “no-code” approach. You can use website plugins like SociableKIT. You can use its free plan if you do not need the premium features. The following are the steps that you need to take.

Step-by-step guide

  1. Sign up to SociableKIT. You will be logged in automatically after you enter your email address.
  2. Create a new solution. Select “Instagram feed” on the drop-down. Enter your Instagram username.
  3. Click the Next button. It will show the customization options like layouts, colors, and more. Click the Save changes button.
  4. Copy embed code. On the upper right, click the “Embed on website” button. Copy the embed code.
  5. Paste on your website. Create a new page or edit an existing page on your website. Paste the embed code where you want the Instagram feed to appear.

Using SociableKIT, you can also display Instagram reels, Instagram hashtag feed, Instagram stories, and more on your website.

Output

Your Instagram feed using SociableKIT can look like the following.

Example Instagram feed #1
Example Instagram feed #2

Thank you!

Thank you for learning from CodeOfaNinja! I hope you learned how to add, embed, or display Instagram feed on your website using PHP.

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? You may use our comments section below or email our team at [email protected]

56 comments

  1. Hey Mike,
    ty for the nice Tutorial. Can u say me how i can get the Instagram Posts filtered by Hashtag, not by User ?
    ty

  2. @Corsari, I see your point, thanks for your suggestion! I’d like to post a comment there but the thread was closed. I’ll reach out to CSS Tricks and try to post a content like this there soon.

    The tutorial only covers the LEVEL 1 source code. If that’s not good enough and if you need more features, you may support us by downloading the LEVEL 2 source code. Thank you!

    1. Hi @Corsari, thanks for sharing the link! It’s good to know about the API changes.

      But the goal of our tutorial above is only to display Instagram posts on a webpage. The tutorial still works as seen on the live demo.

  3. Hello am trying to add an instagram feed on my website but the photos are not showing, what could be the problem please need your help?

      1. Hello @ninjazhai I have used that link and its not helping me, because i don’t want to display my Instagram information, I want to display only five photos to the website from my Instagram thanks for your later reply.

    1. Hello @arshad_arsal , we are unable to replicate you issue. It works on our localhost AND web server as seen on our demo links above. Let us know the exact error message you encounter so we can try to solve that.

      1. I think it is the problem with this script. This on is no longer working You can check the demo here https://goo.gl/KoeCUo But for local host with out the script it is fine. In live demo the page is blank

  4. Hi,

    I noticed this code is causing a 5-6 second TTFB on my site, is there any we can use a $(document).ready on it or call the json with jquery so it doesn’t prevent the server from responding?

  5. Hi Mike,

    Can I make api call from iOS app and load the json reponse in my app using your code?

    1. Hello @Kalpit, you can imitate the how the JSON url above was constructed using your code in your iOS app. Then you can parse the JSON response using your programming language.

  6. Mike, thanks for your efforts with this project. Finally an Instragram feed project that does not require you to jump through all the API hoops just to show my feed [thumbs-up]! I do have a question, All of the images being called up are being formatted in a square format. Unlike Teddy Georgia Waggy issue, I’d like to have the images render in their native format (i.e. if they are portrait, show portrait and if they are landscape, show landscape). Currently, all images regardless of their orientation are being produced in the square format (adding white space above/below or left/right based on the orientation). Is there code that can be added/adjusted to produce this? The reason I’m asking… I have an adjustable image grid application I created that is designed to allow portrait/landscape images to live together. I have a working demo of my application using your core code here; http://edhathaway.com/instagram-gallery . The long & short of my question is… is there a way to display the ‘native’ image without it being squared? Thanks again!

      1. Mike, Thanks for your assistance regarding my issue. However, I have an FYI that might be of assistance to you and/or your users regarding the ‘client token’. If you use the website link mentioned in Step 3.0 and you have ‘no’ or ‘multiple’ registered Instagram client apps, the client token you get in return is not assigned to anything other then your specific username account. Thus, all you can render are the squared image format. To get the correct ‘client token’ specific to one of your active Instagram apps you need to use this URL; https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token -Replace the CLIENT-ID and REDIRECT-URI with the data from an active Instagram app and you’ll get a ‘client token’ that is assigned to this specific Instagram app. From here you can adjust this Instagram client app settings (i.e. show non-square images) as needed. By following these steps I was able to get my extension to show my Instagram images in their native format. With this, everything is PERFECT! Again, thanks for your great code and I’ll be purchasing your 2nd level offering because your efforts need to be rewarded.

      2. Hello @disqus_amRBhZc7Ga , thanks for providing this information, I appreciate it!

        However, I wonder how that link still works for you, we previously used that method and many people emailed me that it does not work anymore.

        I actually just tried it myself earlier, and I got the following error message:
        {“code”: 403, “error_type”: “OAuthForbiddenException”, “error_message”: “Implicit authentication is disabled”}

        Did you do something special? Did you submit your client to Instagram and got approved? We are using the sandbox mode in the tutorial above.

        Thanks for your intention to support our site by purchasing our source code, I really appreciate it!

      3. Mike, if you include the ‘http://’ or ‘https://’ in your authorized domain name (in the Security tab of your Instagram client app) and include this into the path I posted above… you’ll get your access token. I have 5 Instagram client apps and I was able to get a unique access token for each and all worked. Now, I’m not sure how long Instagram will allow this to work but for now and for me, it works unlike using the posted URL (step 3.0) that does not bind to a specific client app. I’d be interested to hear from you or others if this works on your end.

      4. Mike, suggestions… no! Facebook is trying their best to push Instagram’s API as far away from website developers who just want to show their feed. What a shame – IMHO. I did some digging around on the ‘Pixel Union’ site and found that the button you click onto to get an ‘access_token’ is using a very mildly modified URL that I posted above. Their URL is; https://instagram.com/oauth/authorize/?client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&response_type=token -Using this URL (making sure to include your CLIENT_ID & REDIRECT_URL) will ask you to authorize your request (because being in sandbox mode) and once authorized, will push you back to your registered ‘redirect URL’ with a working ‘access_token’. So… for now, either URL will generate an ‘access_token’. Remember… make 100% sure the ‘Disable implicit OAuth’ checkbox is NOT checked or you’ll get an error (as you found out).

      5. @disqus_amRBhZc7Ga , it looks like it works for me now. The feed it fetches is the feed of API client owner. It seems like it cannot be used for other Instagram accounts.

        Did you try to use:
        https://api.instagram.com/v1/YOUR-USERNAME/self/media/recent/?

        Instead of:
        https://api.instagram.com/v1/users/self/media/recent/?

        Did it work?

        Anyway, I think the instructions on our blog above works for people who does not want to create an API client and prefer the square images.

        But I’ll add the instructions for people who need the original aspect ratio as well. Thanks for all your help!

  7. Hi Now that the api for Instagram has changed, where can I find the user id or can we use username instead?

  8. Great article, thanks for sharing. One question. How do you get around the new rate limit of 500 requests per hour?
    Cheers!

    1. Hello @sevensoutbill, glad you liked our article! About your question, we don’t have a workaround for it yet. We’ll try to find out if it is possible to bypass the new limit.

      1. Hey Mike – Here’s what we did. We cache (save json) for an initial request, then any requests for the next 15 sec are served the cached data. After 15 sec we allow another request and refresh the cached data from Instagram.

  9. Now that instagram allows portrait and landscape aspect ratios, not just square, is it possible to style this code so that it crops the images to display them as square? (The way that instagram crops everything to square on a user’s profile feed).

    I’m including an image of how it looks – I’d rather all the images be cropped to square if possible.

    Thanks for the tutorial!
    – Teddy

  10. I got approved for basic permissions on instagram and I want to get the feed with the pictures, comments, followers, following, likes, post for my own analysis. Would your code allow me to do that?

  11. I would like to purchase the pro version but we don’t have Paypal in our company. Is it possible to buy it with just a credit card?

    1. Hello @disqus_UaEBkp74Fp, thanks for your interest in purchasing our code! About your question, you can use your credit card to pay with PayPal, you don’t need to create a PayPal account if you don’t want.

  12. On PHP version lower than 5.4.0

    I get this error

    Warning: json_decode() expects at most 3 parameters, 4 given

    How to solve it?

  13. Hello, do you think it is possible to buy the PRO version with at least the 3 recent comments from each instagram photo? Please let me know the price, thanks!

  14. Thanks for this! Very helpful. Can we use the same access token for ever? Will it change overtime?

    1. Hello @sanojbogoda, sorry for the late reply. About the access token, only Instagram can tell if we can use it forever or if it will change overtime. For now, we enjoy that it works.

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top