In this article, you will see how to get instagram posts in PHP with nice pager.
In my previous post Get Instagram Posts Without any API, I wrote simple code to pull latest 20 instagram posts. Since Instagram recently updated their API, so the result sets of the API calls have been changed. Using the old method, we cannot get the posts by page any more. There is a new method recently introduced to perform the same function.
In this article, I have explained the new method that Instagram has just introduced using the graph api to pull instagram posts.
Get Instagram Posts in PHP Demo
Here is the demo of the script in working condition. Please find a link at the end of the article to download the demo.
<?php $myUserID = '50232398'; $pageSize = 20; $profileUrl = "https://instagram.com/graphql/query/?query_id=17888483320059182&id=".$myUserID."&first=".$pageSize; ?>
In $profileUrl, you can use the same query_id parameter as it is a required parameter and won’t affect your results even if you change it.
<?php $iterationUrl = $profileUrl; $tryNext = true; $limit = 100; $found = 0; while ($tryNext) { $tryNext = false; $response = file_get_contents($iterationUrl); if ($response === false) { break; } $data = json_decode($response, true); if ($data === null) { break; } $media = $data['data']['user']['edge_owner_to_timeline_media']; $found += count($media['edges']); if ($media['page_info']['has_next_page'] && $found < $limit) { $iterationUrl = $profileUrl.'&after='.$media['page_info']['end_cursor']; $tryNext = true; } $nodes = $media['edges']; foreach ($nodes as $thispost) { $post = $thispost['node']; $postId = $post['id']; $type = $post['__typename']; $link = 'https://www.instagram.com/p/'.$post['shortcode']; $picture = $post['display_url']; $message = ($post['edge_media_to_caption']['edges'][0]['node']['text']) ? $post['edge_media_to_caption']['edges'][0]['node']['text'] : ""; $thumbnail = $post['thumbnail_resources'][4]["src"]; $created_time = date('Y-m-d H:i:s', $post['taken_at_timestamp']); } } ?>
To summarize, the code to get instagram posts in PHP is pretty straight forward. A limit has been set to 100 to get only 100 posts but in chunks of 20 post per page. Which can be handy if you are writing a cron job which is going to pull instagram posts from multiple accounts and hundreds of posts for each account.
$iterationUrl variable holds the next call URL to bring next set of 20 posts.
$media[‘page_info’][‘end_cursor’] holds the last post information in the current page, so in every next call we send this value to the API to get next 20 posts starting after this one.
You can get thumbnails of different sizes from this array: $post[‘thumbnail_resources’]
These can be handy in situations where you want optimized images but in good quality.
Source code to get instagram posts in php can be download from here.