Get Photos from Instagram using jQuery

The ready to use examples of getting Instagram media by user ID, by username, by one or multiple tags. Works perfect with new API changes.

#instagram, #JavaScript  /  May 2  /   90

This is the first post in post series about Instagram. There would be posts about working with Instagram API (via PHP and JavaScript) without difficult classes or another similar things. Just ready to use code.

For those who are looking for the complete decision, I have the one. It is the WordPress plugin which allows you to insert Instagram widget with photos of a certain user or (and) by a hashtag(s).

And if you are looking for a post about connection to Instagram API with pure JavaScript, this is it.

Now let’s come back to this post — it consists of three parts and different examples. As you could understand from its heading it is only about getting photos. Another API methods will be described in the next posts.

Small introducion to Instagram API changes. Access token. #


Generate your Access Token in 4 easy steps #

First of all we need a small preparation — for all examples you should specify your Access Token. It is very easy to get it in four steps:

  1. Log in to Instagram and open this page https://instagram.com/developer/clients/manage
  2. Click on the button «Register a New Client».
  3. Fill all the required fields, in Valid Redirect URIs specify https://rudrastyh.com/tools/access-token and click «Register». Then click «Manage» button to obtain both Client ID and Client Secret of your just registered app.
    Instagram Client ID and Client Secret
  4. Use the Client ID and Client Secret to generate access token with this tool. You can find more info there as well.

A few facts about Sandbox Mode #

  • All newly created apps start in Sandbox Mode
  • Apps in Sandbox mode have access only to 20 latest media of an access token owner (and sandbox users invited to your app).
  • To avoid these restrictions you should send your app to approval.

1. By User ID #

In fact, it is the only example in this post that works properly in Sandbox Mode. For Sandbox mode change userid to the access token owner ID or just to self.

var token = 'your access token', // learn how to obtain it below
    userid = 1362124742, // User ID - get it in source HTML of your Instagram profile or look at the next example :)
    num_photos = 4; // how much photos do you want to get
 
$.ajax({
	url: 'https://api.instagram.com/v1/users/' + userid + '/media/recent', // or /users/self/media/recent for Sandbox
	dataType: 'jsonp',
	type: 'GET',
	data: {access_token: token, count: num_photos},
	success: function(data){
 		console.log(data);
		for( x in data.data ){
			$('ul').append('<li><img src="'+data.data[x].images.low_resolution.url+'"></li>'); // data.data[x].images.low_resolution.url - URL of image, 306х306
			// data.data[x].images.thumbnail.url - URL of image 150х150
			// data.data[x].images.standard_resolution.url - URL of image 612х612
			// data.data[x].link - Instagram post URL 
		}
	},
	error: function(data){
		console.log(data); // send the error notifications to console
	}
});

See the Pen EyPbBr by Misha (@rudrastyh) on CodePen.light

2. By a Username #

Of course you can look for user ID in Instagram HTML code each time.

But do not you think that it would be better to get user ID in the code automatically? Especially for your own plugin or application. It is much simplier for every single user of your app to specify a username, not a user ID.

This example isn’t supported by apps in Sandbox Mode.

var token = 'your access token',
    username = 'rudrastyh', // rudrastyh - my username :)
    num_photos = 4;
 
$.ajax({ // the first ajax request returns the ID of user rudrastyh
	url: 'https://api.instagram.com/v1/users/search',
	dataType: 'jsonp',
	type: 'GET',
	data: {access_token: token, q: username}, // actually it is just the search by username
	success: function(data){
		console.log(data);
		$.ajax({
			url: 'https://api.instagram.com/v1/users/' + data.data[0].id + '/media/recent', // specify the ID of the first found user
			dataType: 'jsonp',
			type: 'GET',
			data: {access_token: token, count: num_photos},
			success: function(data2){
				console.log(data2);
				for(x in data2.data){
					$('ul').append('<li><img src="'+data2.data[x].images.thumbnail.url+'"></li>');  
				}
    			},
			error: function(data2){
				console.log(data2);
			}
		});
	},
	error: function(data){
		console.log(data);
	}
});

Can I get Photos of a Certain User Filtered by a Tag(s)? #

Get Instagram photos of a certain user filtered by a tag.

Yes you can. I do not want to overload this post with difficult code, so, I recommend you to download my Instagram plugin for WP — and it doesn’t require access token or application approval! If you won’t use WordPress, you can inspect the plugin code anyway.

3. By a Tag #

This functionality is also very popular. Very easy to implement.

But if your Instagram app is in Sandbox Mode you can only get your own tagged media. And rememeber that your app has access only to 20 recent media. If you want to avoid these restrictions so much you could try to use my WordPress plugin.

var token = 'your access token',
    hashtag='wordcamprussia2015', // hashtag without # symbol
    num_photos = 4;
 
$.ajax({
	url: 'https://api.instagram.com/v1/tags/' + hashtag + '/media/recent',
	dataType: 'jsonp',
	type: 'GET',
	data: {access_token: token, count: num_photos},
	success: function(data){
		console.log(data);
		for(x in data.data){
			$('ul').append('<li><img src="'+data.data[x].images.standard_resolution.url+'"></li>');  
		}
	},
	error: function(data){
		console.log(data);
	}
});

Can I get photos by Multiple Tags? #

Get Instagram photos by multiple tags.

Of course you can, but you should learn more about JavaScript arrays in that case — this requires to make an ajax request for every hashtag and then just rearrange the result data.

If you don’t want to dig into it — download the plugin and look how this is implemented in the code (or just use the plugin — that’s all).

If you have a question, please, leave it in comments — I will answer for everyone.

Only the best of WordPress

Subscribe to this weekly newsletter to receive the latest blog posts by email.I respect your privacy. Your email is safe with me.

Comments 90

  • This is the simplest script I’ve found to get photos via the Instagram API, and your instructions were the clearest. Thank you!!

  • if i have a scenario like this : i have an instagram account, ex : @jonsnow. i want to create a web app using php, which can reply a comment with my account (@jonsnow) it is possible? my algorithm is first, i search a photo with a tag. than i want to get the photo caption, then i want to give/reply a comment with my account.

  • I notice you say “If you won’t use WordPress, you can inspect the plugin code anyway”. I do not have a WP site but I want to mess with some of this plugin’s code in a personal product. 2 questions:
    1. Can I definitely see the source code if I buy the plugin to copy and alter for my own app?
    2. Will I still be restricted by the sandbox return results?

    • MishaAuthor June 16, 2016 at 03:42

      Hi Joe,

      1. Yes, you can do it, but in the latest version of the plugin it is not so simple as before ( you will need good knowledge of PHP and PHP/JS beautifier ).
      2. No you won’t be restricted.

  • Awesome post, the better one I have found that explain and help to get the Access token and without the need of other libraries.

    Do you know if Is it necessary to submit the instagram app for review if you are only using it to grab the most recent photos from the instagram account to show them in the company website?

  • joseneas July 4, 2016 at 16:41

    Hi

    It’s possible to send a Image and hashtag to the user timeline?

    thanks

  • This is not Javascript. This is JQuery. If we wanted JQuery, we would’ve come looking for “JQuery.” The title is misleading.

  • That’s amazing article as I have know. Thank you so much.

  • This still work ?

  • firebuggirl August 8, 2016 at 02:15

    Hi,

    When I follow the instructions and attempt to get an access token I receive this error:

    “code”: 400,
    “error_type”: “OAuthException”,
    “error_message”: “Invalid Client ID

    Why is this happening?

    Thanks!

  • Is there a way to fetch my account’s liked photos/videos?

    Thanks!

    • MishaAuthor August 15, 2016 at 10:08

      Hi Marcelo,
      yes, you can just add the IF statement:

      for(x in data2.data){
      	if( data2.data[x].likes.count > 0 ) {
      		$('ul').append('<li><img src="'+data2.data[x].images.thumbnail.url+'"></li>');
      	}
      }
      • Can this work for Sandbox accounts?

        Its not working for me.

        • According to the API I can implement likes within sandbox but a limit 30/hour

          im not sure how to incorporate the URL to get my likes

          https://api.instagram.com/v1/media/{media-id}/likes?access_token=ACCESS-TOKEN

          with your code provided.

          Any help would be appreciated.

          • MishaAuthor March 17, 2017 at 10:17

            Hi Has,

            this endpoint https://api.instagram.com/v1/media/{media-id}/likes?access_token=ACCESS-TOKEN doesn’t work with sandbox account.

        • OMG the issue was my function was data NOT data2 as exampled!

          But I still have one question.

          This is only controlling the media I have personally posted on my account and liked (my own content).

          I thought and would like to show any media (pictures) on Instagram I have liked to show up in my feed.

          Is that possible? I have tried modifying the URL parameter to no success.

          • MishaAuthor March 17, 2017 at 10:20

            If you want to show all media you liked you need to use this endpoint https://api.instagram.com/v1/users/self/media/liked?access_token=ACCESS-TOKEN but it also requires public_content scope to be approved.

  • Great tutorial. I really enjoyed it. :)

    I was wondering if you had the ability for a search function to populate images via hashtag?

  • *For the user to input themselves that is (Sorry for not clarifying before). Thanks.

    • MishaAuthor August 18, 2016 at 10:37

      Hi Valerie,

      My plugin can get images by hashtags, currently it can not filter user images by a specific tag (well, it can, but this functions doesn’t work as expected), but I’m working on it now :)

  • hi developer, thank for your job.

    3 questions for you

    1) I did understand why in Valid Redirect URIs I need to specify this url https://rudrastyh.com/tools/access-token ? I can’t put my website url http://www.exemple.com ?

    2) I would like to view pictures about other public account?i s it possible ? Or just own account ?
    3) at the end, is it possible found results by hashtag from all profile. I would like to create an aggregator by instangram hashtag

    thank you Rud

    • Hi,
      1) Try to put your website there and look what happens :) It is required to specify url to the tool, after receiving Access Token you can change it if you want I suppose.

      2) Other accounts are possible in two cases: a) approved access token b) using my plugin.

      3) Profile pictures filtered by a hashtag currenly is not supported.

  • does it possible nowadays for me to show timeline photos based on hashtags, example #helloworld ?
    because even snapwidget(instagram timeline viewer for website) remove their ability to showing all photos based on hashtags

  • Arrogant Ambassador October 29, 2016 at 11:48

    This is a fantastic little tool. Thanks for creating it.

  • Hello Misha,

    Do you know how to search for tags with Ruby?

  • is any option to move my image with some rotation with change position.

  • Hey Misha, thanks a lot for this tutorial.

    I have a problem tho, I get the acces token with my personal account, but when I want to retrieve a feed by hashtag, I get an empty array.

    The same happens when i search for a random user, even when their accounts are public.

    I have copied and pasted the code exactly as you show here, replacing only the token

    • MishaAuthor January 4, 2017 at 22:35

      Hi Leo,

      since June 2016 Instagram made some changes in their API, if your application is not approved, you can get ONLY 20 latest photos of your account (the owner of the access token).

      But you can consider using this plugin – it allows to get photos by tags and from any public account without an access token.

    • When you create an application to get a token on instagram, it is created on sandbox mode. When on sandbox mode, you can only query your own content, and you’ll only get 20 results.

      You cannot submit the application for approval, I mean you can but it’s worthless, as any useful scenario won’t be approved. For instance, searching for hashtags and displaying content on your website.

      So, if you create your token and query the instagram api for pictures tagged with #somehashtag

      https://api.instagram.com/v1/tags/somehashtag/media/recent?access_token=[token]

      it will only return images tagged that were published using your account. If you don;t have any, you’ll get an empty array.

  • sorry, when i get myself’s user detail, i get results, but when i want to get other’s user detail, it return error with 404.l

  • Carolina Ferreira February 6, 2017 at 23:38

    Hey!
    Thank you so much for this explanations, but yet since I’m quite new to the programming world I’m not getting the result I want.
    I made a instagram token, and my objective is put that on a website I made, specially in a page that I created.

    I tried to copy the javascript code, but I can’t get any results when I paste it.

    Any ideias to resolve this?

    Much appreciated

  • Hey! Great post :)

    I encountered a problem when trying to access the pictures posted with a tag from a specific account. I got back an OAuthPermissionException that I’m not sure how to fix. I thought it might have something to do with the security settings in the client management on instagram.com/developer but even after unchecking “Disable implicit OAuth” I still get the exception.
    Any idea about what I’m missing? My URL looks like this https://api.instagram.com/v1/tags/MY_TAG/media/recent?access_token=MY_ACCESS_TOKEN

    Thanks either way :)

  • hello, how i can show location of tagged photo on map?

  • hi, I have been able to put your code into my website and it works really good.
    However, can you help me showing the photo caption and the location as well (even as a text only)?
    thank you.

    • Hi,

      data.data[x].caption.text — for caption text,
      data.data[x].location.name — for location text,

      info about location coordinates is in my above comment.

      • I just tried it, it shows a broken image file, I guess it has something to do with the “img src=”. I honestly don’t know. If you will you can check on my web how it turns out: http://fazr.in and tell me what do you think.

        thanks for your prompt reply

        • I found this piece of code on your website:

          $('ul').append('<li><img src=\"'+data.data[x].location.name+'\"><\/li>');

          Interesting to know, why you’re trying to set location name (such as Big Ben) as an image src?

          Working codepen example is above. It is easy – use it to find out what to do.

  • Incredibly helpful, thank you so much!

    I am having a problem with the javascript, though. I only know CSS and HTML, and on my site, some other elements use the tag, so my instagram feed has been showing up everywhere is used. How might I change the code so that my feed only shows in the one instance of ?

    Thanks in advance!

  • Hi Misha, solid plugin.

    I’m looking to make a button with command to refresh my list of instagram pictures using your basic sandbox example code above. But I can’t figure it out. I’ve come across listview refresh command but I’m assuming it had something to do with refreshing the URL provided in the ajax code.

    So I don’t want to page to refresh, just the content dynamically on the press of a button or even automatically after a set amount of time.

    Any help would be appreciated.

    P.S – I was wondering if you would release this plugin for non WordPress use so I can use it in my case a phone gap app I’m developing.

    • MishaAuthor March 12, 2017 at 08:36

      Hi Has,

      currenly it doesn’t, but I plan to add it in the next version. But not sure that the plugin will be for non-WordPress :) WordPress one love.

  • Hi,

    I did create CLIENT ID and got token access,but when I tried your code and replace it with my token access I got nothing. here it is:

    <!DOCTYPE html>
    <html>
     
    <style>
    #rudr_instafeed{
      list-style:none  
    }
    #rudr_instafeed li{
      float:left;
      width:200px;
      height:200px;
      margin:10px
    }
    #rudr_instafeed li img{
      max-width:100%;
      max-height:100%;
    }
    </style>
     
    <body>
    <ul id="rudr_instafeed"></ul>
    <script>
    var token = '4865278193.fbd1066.fd2744909506428481ef2e74c5bed003',
        num_photos = 10;
    $.ajax({
    	url: 'https://api.instagram.com/v1/users/self/media/recent',
    	dataType: 'jsonp',
    	type: 'GET',
    	data: {access_token: token, count: num_photos},
    	success: function(data){
     		console.log(data);
    		for( x in data.data ){
    			$('ul').append('<li><img src="'+data.data[x].images.low_resolution.url+'"></li>');
    		}
    	},
    	error: function(data){
    		console.log(data);
    	}
    });
    </script>
    </body>
    </html>

    what would you advice me to do please?

  • Gorge Gith April 12, 2017 at 23:06

    Hi Misha,
    Can you please help me Facebook,how i get facebook URL to numeric id?

    • MishaAuthor April 13, 2017 at 11:52

      Hi,

      I’m not sure about the correct way to do it, but when I need to get my profile ID, I usually right click on my cover image in profile, then Inspect, then in the source code I’m looking for fbid parameter :))

      For me it takes less than a minute.

  • Jusis Pitch April 13, 2017 at 17:20

    Hi Misha,
    I want to fetch only Instagram profile picture by username for my website.Is there anyway to find it means user put Instagram username and and i fetch information about user like user profile picture and name.In your code access token work only for my profile any option for other

    • MishaAuthor April 14, 2017 at 07:23

      Hi Jusis,

      Yes, there is a way to get information for other users, but you have to approve your application in Instagram. This endpoint /users/{user-id}/?access_token=ACCESS-TOKEN.

      If you want to get info by username, add also this /users/search?q={user-name}&access_token=ACCESS-TOKEN

  • Richard Nash April 25, 2017 at 19:22

    Do you have a version this code snippet without jquery? That would be awesome :-)

  • Hi Author,

    The code is working fine for me. But I want the live feed with the text,comment and post details. How to do that? Can you help me to sort out this issue?

    • MishaAuthor May 2, 2017 at 06:57

      Hi,

      use console.log( data ); function to see all the returned values in your browser console. If the received information is not enough for you, it means in most cases that your app should be submitted for approval. Proceed to the official Instagram API reference then.

  • Am I able to get latest 20 photos for any instagram user or only just my account. Does the api allow getting any users photos or just your own.

  • Hi Misha,

    your code is awesome. but is there a way that when you click the image it will redirect back to the instagram page and original photo?

    thanks in advance

  • I’m using sandboxed mode apps,instead of userid what we need to mention?

    • MishaAuthor May 31, 2017 at 16:53

      https://api.instagram.com/v1/users/self/media/recent or https://api.instagram.com/v1/users/self depending on what you want to get.

  • Shurvir Mori June 16, 2017 at 11:50

    thanks, it works.

  • {“error_type”: “OAuthException”, “code”: 400, “error_message”: “Redirect URI does not match registered redirect URI”}

  • Thanks!! Its work great !!

Leave your question or feedback

phpjsHTMLCSSSQLCode
Please, enter a comment
Please, enter a name
Incorrect email