Display Instagram Feed on your website using PHP

Previously, we learned how to display Facebook page posts feed on your website using PHP.

Today, our tutorial will explore integrating Instagram into your website by displaying your Instagram feed using PHP. This can be a great way to showcase your content and keep your website visitors engaged with your brand.

Using PHP, we can easily connect to the Instagram API and retrieve your latest posts, allowing them to be displayed on your website. Any new content you upload to Instagram will automatically appear on your website, saving you the hassle of manually updating your website every time you post something new.

Following this tutorial can bring your Instagram content to your website, providing your audience with a seamless browsing experience and keeping them updated with your latest content. So, let’s dive in and start displaying your Instagram feed on your website using PHP!

Display Instagram feed on website using PHP

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.

Here are the steps to display the Instagram feed on a 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 retrieve your Instagram photos and videos programmatically. 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 exact 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 get 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.

We will also cover using a website plugin to achieve the same output. This is best for people who do not want to code. Continue reading below.

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. Follow this tutorial: embed your Instagram feed on your website. You can use its free plan if you do not need the premium features.

Step-by-step guide

Follow the steps below to display your Instagram feed using a website plugin.

  1. Sign up for 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

What’s Next?

Today we have learned how to show your Facebook page events on your website. Did you know that you can also display a Twitter feed on your website?

Let us go to the next tutorial: How to display a Twitter feed on website?

[adinserter block=”3″]


Comments

58 responses to “Display Instagram Feed on your website using PHP”

  1. Erick Olivares Avatar
    Erick Olivares

    Thanks! This was very helpful. Major Props

  2. ninjazhai Avatar
    ninjazhai

    Hello @disqus_orqGKcOK5V, glad to hear it was very helpful to you! Thanks for your kind words!

  3. Sanoj Bogoda Avatar
    Sanoj Bogoda

    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.

  4. 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!

    1. Hello @disqus_8MxqLU3EQm, yes I think it is possible. We’ll update the pro version above with this feature this end of February 2016.

  5. Impactious Avatar
    Impactious

    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?

  6. You can try to do it this way


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

  7. Scansail - tp Avatar
    Scansail – tp

    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.

  8. 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?

    1. Hello @disqus_6BtDIsxQnh, we are currently working on those features. Send your email to my email [email protected] so we can keep you updated.

  9. Teddy Georgia Waggy Avatar
    Teddy Georgia Waggy

    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

    1. Hello @Teddy, thanks for the idea! I will update the code soon.

      To answer your question, yes it is possible with CSS. You have to make the images a ‘background’ of your div tag.

      Please see this demo and view the css:

      https://www.codeofaninja.com/demos/display-facebook-photos-pro/index.php?fb_page_id=227228333969461

  10. Sanchit Avatar
    Sanchit

    Instagram has been changed its api now the above process does not work.. 🙁

    1. Hello @disqus_CPunhLEVgZ, thanks for reporting, we are working on the new update. We will update the code soon.

      1. Sanchit Avatar
        Sanchit

        Thank You @Mike.

      2. Sanchit Avatar
        Sanchit

        Thank You @Mike

        1. You’re welcome @reach_sanchit_gupta!

  11. sevensoutbill Avatar
    sevensoutbill

    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. sevensoutbill Avatar
        sevensoutbill

        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.

        1. @sevensoutbill , awesome, thank you for sharing your solution with us!

  12. amadhav1 Avatar
    amadhav1

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

    1. Hi @amadhav1, for now we cannot use usernames, only the user with specified access token. Please see the updated tutorial above.

  13. Thank you for a great simple tutorial, had a custom version up and running in no time.

    1. Hello @d@disqus_1rKIRNDjHJ , glad it works for you! Your page looks cool, would you share the link to us?

      Please share our site to one of your friends if you have time, thank you!

  14. 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. Hello @disqus_amRBhZc7Ga , thanks for the kind words! About your question, my answer is in section 10.0 above. You’re welcome.

      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.

        1. 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!

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

          2. @disqus_amRBhZc7Ga ‘http://’ or ‘https://’ is already included in my client but it still didn’t work. What I did was Edit > Security Tab > Uncheck ‘Disable implicit OAuth’, I did not see this option before.

            I can see the access token at the URL. But when I tried to use it with the JSON url:

            https://api.instagram.com/v1/users/self/media/recent/?access_token=MY_CLIENT_ACCESS_TOKEN&count=9

            It did not work. Any suggestions?

          3. 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).

          4. @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!

  15. Kalpit Seksaria Avatar
    Kalpit Seksaria

    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.

  16. Edd Allen Avatar
    Edd Allen

    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?

  17. Hello @Edd Allen, if that’s your case, you can always call the PHP file with jQuery .load(), or maybe use React. We have a React tutorial if you’re interested: https://www.codeofaninja.com/2016/07/react-crud-tutorial.html

  18. Arshad Arsal Avatar
    Arshad Arsal

    This is working fine in local host, but in live the feeds are not showing

    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. Arshad Arsal Avatar
        Arshad Arsal

        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

        1. Hello @arshad_arsal , the following script is still working:

          As seen in our LEVEL 1 live demo: https://www.codeofaninja.com/demos/display-instagram-feed-level-1/

  19. Ruth Asiimwe Avatar
    Ruth Asiimwe

    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. Hi @ruth_asiimwe , please post the error message you encounter. Make sure your server support JSON and allow_url_fopen.

      Another option is to use a website plugin like https://www.displaysocialmedia.com/embed-show-display-instagram-feed-on-website/

      1. Ruth Asiimwe Avatar
        Ruth Asiimwe

        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. The website plugin have options to hide your Instagram profile information and limit the number of photos to 5.

  20. bskinny Avatar
    bskinny

    thank you very much

    1. You’re welcome @bskinny!

  21. Hi @rodrigozuluaga, Instagram API can only render 33 photos at a time.

  22. Hi Mike
    I suggest to clarify a bit in regard of the Instagram’ API changes introduced in summer 2016

    Like is described here
    https://css-tricks.com/everything-need-know-instagram-api-integration/

    especially about the Sandbox concept

    Do you agree?

    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.

  23. @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!

  24. Thorsten Renz Avatar
    Thorsten Renz

    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

    1. Hi @thorsten_renz, thanks for the kind words! Unfortunately, we don’t have tutorial for an Instagram hashtag feed. But here’s another option https://www.youtube.com/watch?v=u4tsduf6kqU

  25. You’re welcome @rdsilambarasan!

  26. your dark mode button

    1. Hi there, do you prefer to use dark mode? Did it work for you?

Leave a Reply

Your email address will not be published. Required fields are marked *