Get Images from Instagram using PHP
Of course, it is also possible to get Instagram feed using JavaScript as well.
As for me, the JavaScript method has two major advantages.
- Asynchronous AJAX requests do not affect on website response time. cURL in PHP does.
- If you use PHP cache (for example WP Super Cache plugin for WordPress), the JavaScript method allows you to avoid feed caching.
Ok, so, the post is about PHP connection to Instagram API, isnโt it? ๐
Step 1. Instagram API cURL connection
First of all you have to insert this function somewhere into your code, otherwise none of the following examples will work. If you use WordPress insert the function to your current theme functions.php
file.
function rudr_instagram_api_curl_connect( $api_url ){
$connection_c = curl_init(); // initializing
curl_setopt( $connection_c, CURLOPT_URL, $api_url ); // API URL to connect
curl_setopt( $connection_c, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
curl_setopt( $connection_c, CURLOPT_TIMEOUT, 20 );
$json_return = curl_exec( $connection_c ); // connect and get json data
curl_close( $connection_c ); // close connection
return json_decode( $json_return ); // decode and return
}
Step 2. Instagram Access Token
Instagram API doesnโt work with Client ID anymore, now every API connection requires Access Token.
Step 3. Get posts / photos from Instagram
According to the latest Instagram API changes, until you approve your application you can get only the latest 20 media of the access token owner. It means that only the one example from this post will work good and only if you specify your own username.
By a tag
In case you want to use a lightbox plugin, you should place the URL to the maximum size image into the link href
attribute โ $post->images->standard_resolution->url
contains the URL to 612ร612 image (the max resolution in Instagram).
$access_token = 'YOUR ACCESS TOKEN';
$tag = 'wordcamprussia2015';
$return = rudr_instagram_api_curl_connect('https://api.instagram.com/v1/tags/' . $tag . '/media/recent?access_token=' . $access_token);
//var_dump( $return ); // if you want to display everything the function returns
foreach ( $return->data as $post ) {
echo '<a href="' . $post->images->standard_resolution->url . '"><img src="' . $post->images->thumbnail->url . '" /></a>';
/*
$post->images->standard_resolution->url - URL of 612x612 image
$post->images->low_resolution->url - URL of 150x150 image
$post->images->thumbnail->url - URL of 306x306 image
$post->type - "image" or "video"
$post->videos->low_resolution->url - URL of 480x480 video
$post->videos->standard_resolution->url - URL of 640x640 video
$post->link - URL of an Instagram post
$post->tags - array of assigned tags
$post->id - Instagram post ID
$post->filter - photo filter
$post->likes->count - the number of likes to this photo
$post->comments->count - the number of comments
$post->caption->text
$post->created_time
$post->user->username
$post->user->profile_picture
$post->user->id
$post->location->latitude
$post->location->longitude
$post->location->street_address
$post->location->name
*/
}
By a username
Instagram API allows to get user feed only by a user ID. It can mean only the one thing โ we should get the User ID at first.
$access_token = 'YOUR ACCESS TOKEN';
$username = 'rudrastyh';
$user_search = rudr_instagram_api_curl_connect("https://api.instagram.com/v1/users/search?q=" . $username . "&access_token=" . $access_token);
// $user_search is an array of objects of all found users
// we need only the object of the most relevant user - $user_search->data[0]
// $user_search->data[0]->id - User ID
// $user_search->data[0]->first_name - User First name
// $user_search->data[0]->last_name - User Last name
// $user_search->data[0]->profile_picture - User Profile Picture URL
// $user_search->data[0]->username - Username
$user_id = $user_search->data[0]->id; // or use string 'self' to get your own media
$return = rudr_instagram_api_curl_connect("https://api.instagram.com/v1/users/" . $user_id . "/media/recent?access_token=" . $access_token);
//var_dump( $return ); // if you want to display everything the function returns
foreach ($return->data as $post) {
echo '<a href="' . $post->images->standard_resolution->url . '"><img src="' . $post->images->thumbnail->url . '" /></a>';
}
Returned Values
Both /users/{ID OF A USER}/media/recent
and /tags/{NAME OF A TAG}/media/recent
return the same array of objects. View the examples above.
Get Instagram Profile Picture using PHP
You probably understood how to do it from my previous example, but anyway I would like to highlight this moment.
In case you want to do it, you have to use the following endpoint /users/search?q={USER ID}
, example:
$access_token = 'YOUR ACCESS TOKEN';
$username = 'rudrastyh';
$user_search = rudr_instagram_api_curl_connect("https://api.instagram.com/v1/users/search?q=" . $username . "&access_token=" . $access_token);
echo '<img src="' . $user_search->data[0]->profile_picture . '" />;
This endpoint allows you to display not only a profile picture of a user, you can use print_r( $user_search->data[0] )
to find out what else.
Related

Misha Rudrastyh
Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.
Need some developer help? Contact me
Very nice..
Thanks!
Hello Misha! Nice Blog!
I have a question:
Is it possible to obtain the photos that I give “Like” from my Instagram account with the Instagram API in PHP?
Thank you Misha!
Hugs!
Hello! Thank you! :)
Yes, just use this
/users/self/media/liked
API endpoint. But I’m afraid you should approve your Instagram app forpublic_content
scope first.Thank you for the answer!
I’m waiting for the Instagram verification for
public_content
.Can you show me any example with
/users/self/media/liked
to see this photos?Thank you very much Misha!
Hugs!
You can use this example I think, just replace this line
with this:
Thanks for the post, it was really useful for me!
I have been dealing with an issue that could be helpful for someone: I just want to display my last posts, so I don’t need my app to be reviewed and approved (you can get last 20 posts without that).
The point is that I was getting the error “This client has not been approved to access this resource.” when making this call: https://api.instagram.com/v1/users/search?q=[user_name]&access_token=[token], so I couldn’t get my user ID.
Then I discovered that I don’t need my user id since I can use this call: https://api.instagram.com/v1/users/self/media/recent?access_token=[token]
Hope it’s useful sometime!
Hi Javier,
thanks for sharing this info!
code is working nice….
Hi,
Thanks for this great code! Something strange is happening in my case. I put everything as indicated and it works. After a few minutes, I stopped being able to see the photos, going blank.
Any idea what that might be?
Hi Filipe,
No ideas :) I need more information at least.
Hello, it;s possibile to limit numbers od feeds to i.e 3?
I found it – just add
&count=3
at the end of instagram request, i.e.$return = rudr_instagram_api_curl_connect("https://api.instagram.com/v1/users/" . $user_id . "/media/recent?access_token=" . $access_token . "&count=6");
Hello, ok, great :)
Hello Misha
Thanks for the great code.
Can you please share the code to get photos from combination of hashtag+ specific location
Thanks
Hello Max,
Currently I have no ready code for this, sorry.
Hi Misha,
Thanks for your post. I didn’t get what I was willing but I am a little bit closer.
I would like to display some user information (behind a autorization) like: account details, number of like of each post, average of likes…
It is possible with the information you shared in this post?
Thank you
Very nice, thank you! I wanted to link the photo to the original Instagram post instead of a picture file, so I used $post->link for href instead. Worked perfectly.
great work!
How I can limit photos. I jus need 4 images.
Thanks
So what do you do with this snippet? Can you please show it in the context of your by_username sample?
Ok, in the context of a username it will be like this:
The snippet is not working on my end. :(
Where did you use it?
So what the heck does a person set the redirect uri to? I am developing on my local machine.
NEvermind, I figured out you have to set the callback uri to the one provided by your token generator.
good job thank!
Hi dev,
i am using this and it works great, but i have one small problem, i dont get all photos tagged with some tag. For example i have 6 photos on my instgram tagged with “example-tag”, but i only get one, or in some other cases 3,4,6, but in most cases not all.
Is there any solution for this?
Thank you very much.
not work for me..
Warning: Invalid argument supplied for foreach()
print_r($return);
Hello, I have the same problem:
What may be the solution?
Thanks,
Gergo
Here is the solution:
1.
$user_id = $user_search->data[0]->id;
changed toself
2. I’ve got an error, when I’ve try to print the $return:
3. I’ve regenerated the token
4. The new token is different from the old one – it’s interesting, because it worked properly few weeks before.
5. In this case with the new token, pictures are visible on the site :)
Hey Gergo,
Thank you for your comment ๐
I’m glad you’ve figured it out!
Add this line for localhost!
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
It shows an error for me but it’s because the path isn’t ok , is someone else have the same problem try to change the path, the corect paths are here:
https://www.instagram.com/developer/endpoints/users/
I am getting an error when using the curl connect. The $user_search returns:
Instagram doesn’t work anymore.
D’oh! Well that sucks. ๐
Thanks
Yes, it is sad ๐
You can check the new instagram graph api platform https://developers.facebook.com/products/instagram/. Maybe you can do something with it.
Obviously, since I was looking here, I am trying to find a very clean way to show 5 or 6 of the last photos of an Instagram feed on WordPress. Plugins always seem too bulky and try to lock you into a layout or theme. I just want the images and I will handle the layout.
Do you have any suggestions?
Thanks!
Hashtag feed doesn’t work anymore?
Hey,
This tutorial should help you.
Thank you Misha,
I managed to fetch with the Jquery. Anyways Thank you :)
Ok, great ๐
Grate code
So, instagram API will be removed in this year.
Can we get instagram photos without API ?
Yes, we can do it this way without API.
is it possible any more to get photos by tag ?
https://www.instagram.com/developer/endpoints/
as i dont see that endpoint :(
Hey,
Everything is possible ๐
Instagram is closing its API, at this moment we still have the possibility to get photos and info of an access token owner. Tags were closed long time ago, at first time it was allowed only for approved applications, now is completely closed.
What are the solutions:
i can get my own data using this script, but failed to fetch other user’s instagram photos using their userids.
i tried with add diffrent username but failed to get feeds: https://api.instagram.com/v1/users/” . $user_id . “/media/recent?access_token=” . $access_token
actually as per our website work flow, we are fetching other users photos using instagram post URL and then like for each post by unknown users. and they will earn point and then purchase some product from our site.
users purchase plan packages for like,comment & follows
users earn point using activity by liking, commenting & following one by one, and purchase our product using earned point
please help me !
and sorry for my bad english
Hi Raj,
Is your Instagram application approved?
I can’t generate my access token, it said :
{“error_type”: “OAuthException”, “code”: 400, “error_message”: “Redirect URI does not match registered redirect URI”}
Hi Orin,
So… are you sure that you configured redirect url in your app?
Hi Misha,
I’ve been reading your previous post on how to add Instagram feed on WordPress. Been looking for the right method to do it for my website. While looking for an answer I ended up more confuse than before.
On my quest to answer, I understood that in order to fetch Instagram’s post on my app or website, I would:
1) Need to have a Facebook Page and connect that page to the Instagram Business Account;
2) Need to register a new Facebook App with a developer account (see https://developers.facebook.com/docs/apps/register);
3) Need to get an access token for user and figure out new App ID using their tool https://developers.facebook.com/tools/explorer/;
But to register my App I need to have an official paper with a company nameโฆ
So my question is, how come your method above seems to work without having to do all these steps?
Are your methods are all using Instagram API v1 โ that fetches a JSONP from the API Url (from
https://api.instagram.com/v1
/) ? If so, does that mean that all current code will be deprecated in early 2020 according to https://www.instagram.com/developer/ .Hi Johnathan,
Yes, it seems that most of the code related to the old API will be deprecated and must be updated.
But there is still a solution here, which is going to work after 2020.