Get Photos from Instagram via PHP

PHP code samples of getting media from Instagram by a username or by a tag. With new API support.

#Instagram, #PHP  /  August 9  /   21

Of course, such lightbox viewers like Fancybox can be easily used if you get Instagram feed via 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. Prepare. Function to set up cURL connection to Instagram API #

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. Still Prepare. Instagram Access Token #

Instagram API doesn’t work with Client ID anymore, now every API connection requires Access Token.Do not be afraid — you can easily get it using this tool.

Step 3. Get posts / photos from Instagram #

According to the new Instagram API changes, until you approve your application you can get only the latest 20 media of youself. It means that only the one example from this post will work good and only if you specify your own username.

If you don’t want to deal with the code and access tokens, you can download ready to use plugin for WordPress. It doesn’t require an access token and has no restrictions.

By a tag #

As we want to use Fancybox plugin (or another lightbox) we 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('' . $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 . '" class="fancybox"><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

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("" . $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("" . $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 . '" class="fancybox"><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.

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 21

  • Captain Bacon February 4, 2016 at 15:43

    Maybe I got a step wrong?
    it returns me the following error

    Warning: Invalid argument supplied for foreach() in ...
    • MishaAuthor February 5, 2016 at 11:29

      Try to print_r( $return );exit; (before the loop). What is there?

    • same happening here. Also, if I access the api url directly I get this:

      {“meta”: {“code”: 200}, “pagination”: {“deprecation_warning”: “next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead”}, “data”: []}

  • Everaldo Matias December 12, 2016 at 01:31

    Very nice..

  • Sarath Hari February 8, 2017 at 10:21

    I am getting an error like “Trying to get property of non-object”. Can i run this script in localhost ?

  • 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!

    • MishaAuthor March 4, 2017 at 15:53

      Hello! Thank you! :)

      Yes, just use this /users/self/media/liked API endpoint. But I’m afraid you should approve your Instagram app for public_content scope first.

      • Thank you for the answer!
        I’m waiting for the Instagram verification for


        Can you show me any example with


        to see this photos?

        Thank you very much Misha!

        • MishaAuthor March 4, 2017 at 18:45

          You can use this example I think, just replace this line

          $return = rudr_instagram_api_curl_connect('' . $tag . '/media/recent?access_token=' . $access_token);

          with this:

          $return = rudr_instagram_api_curl_connect("" . $access_token);
  • 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:[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:[token]

    Hope it’s useful sometime!

  • 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?

  • Hello, it;s possibile to limit numbers od feeds to i.e 3?

    • I found it – just add


      at the end of instagram request, i.e.

      $return = rudr_instagram_api_curl_connect("" . $user_id . "/media/recent?access_token=" . $access_token . "&count=6");
    • MishaAuthor August 10, 2017 at 20:32

      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


Leave your question or feedback

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