Get Photos from Instagram using jQuery

The ready to use examples of getting Instagram media by user ID, by username, by a tag. Works perfect with new API changes.

#Instagram, #JavaScript  /  August 9  /   113

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 by a hashtag.

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. Currently I do not have ready code for this, but it is in my task list.

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 — this functionality is also in my task list :)

If you have a question, please, leave it in comments — I will answer 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 113

← Older
  • Thank you for the great article!
    I`m trying to pull, lets say, a quantity of comments for the latest post done.
    But i get a console error “Uncaught TypeError: Cannot read property ‘count’ of undefined”
    in the line where i set var postdate

    var token = .....
    (function update2() {
    $.ajax({
      url: 'https://api.instagram.com/v1/users/self/media/recent',
      dataType: 'jsonp',
      type: 'GET',
      async: true,
      data: {
        access_token: token,
      },
      success: function(data) {
          var postdate = data['data']['comments']['count'];
          $("#instagram-latest").text(postdate);
      },
      error: function(data) {
        console.log(data);
    }
    }).then(function() {
          setTimeout(update2, 600000);
       });;
    })();

    I dont get why it cannot see data path properly?

    • Welcome!

      It looks like you forgot about:

      data: {
      	access_token: token,
      	count: num_photos
      },
      • But i dont need photos)

        I need likes-count, or post date\time.

        Here`s a fiddle
        https://jsfiddle.net/CapablancaYEAH/y86385eh/

        So if u open develop console, there is a mistake
        var postdate = data[‘data’][‘comments’][‘count’];
        Uncaught TypeError: Cannot read property ‘count’ of undefined

        If you know how to overcome that, i would be grategul!

      • I see.

        Not sure if everything is correct there, but relating to the count error, your code should look like this:

        for(x in data.data){
        	$("#instagram-latest").append( data.data[x].comments.count );  
        }
        • Misha, god bless you! You`re a very talented coder, keep it up!
          That works!

          Thank you!
          Just need to figure out, why it`s giving me info not for the last post, but seems for ALL time :33

        • ahhh…. figured it out too!
          thats why i need count in data{} ) to set the amount of info i need)

          God bless you again!

  • Hi Misha,
    Do you know how to retrieve the image urls making the images in the feed clickable, therefore taking you to their respective instagram posts?

    Thanks!
    Anna

    • disregard, I believe I found your response to another question a few pages back…

      $('ul').append('<a href="' + data.data[x].link + '"></a>');

      thanks for sharing and for replying to everyone’s questions, not many do!

  • hi. tanks for your article.now just a little question.how can I link my photos to their instagram account??

Leave your question or feedback

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