30

I need to get some pictures which have a specific hashtag using PHP ? Any help will be awesome, or hint ?

6 Answers 6

26

Here's another example I wrote a while ago:

<?php       
    // Get class for Instagram
    // More examples here: https://github.com/cosenary/Instagram-PHP-API
    require_once 'instagram.class.php';

    // Initialize class with client_id
    // Register at http://instagram.com/developer/ and replace client_id with your own
    $instagram = new Instagram('CLIENT_ID_HERE');

    // Set keyword for #hashtag
    $tag = 'KEYWORD HERE';

    // Get latest photos according to #hashtag keyword
    $media = $instagram->getTagMedia($tag);

    // Set number of photos to show
    $limit = 5;

    // Set height and width for photos
    $size = '100';

    // Show results
    // Using for loop will cause error if there are less photos than the limit
    foreach(array_slice($media->data, 0, $limit) as $data)
    {
        // Show photo
        echo '<p><img src="'.$data->images->thumbnail->url.'" height="'.$size.'" width="'.$size.'" alt="SOME TEXT HERE"></p>';
    }
?>
7
  • Do you know of any way to get past the limit of 20?
    – Staysee
    May 14, 2013 at 15:28
  • @Staysee See answer below.
    – kexxcream
    May 20, 2013 at 13:52
  • 1
    @kexxcream I'm running your API and I want to getTagMedia for the hashtag #thesouthfarm. Problem is that I only get my own images with that tag. Not my friends. Is there some limitations there?
    – Ismailp
    Jun 20, 2013 at 18:04
  • 1
    @kexxcream sorry for that! Found out that the users had private profiles and thus I could not fetch teh photos! :)
    – Ismailp
    Jun 22, 2013 at 12:18
  • 1
    With the latest version of the Instagram-PHP-API wrapper you need to pass the limit to the getTagMedia() method: $instagram->getTagMedia($tag, 5); and then replace the foreach line with foreach($media->data as $data) {. (Also, the easiet way to load the wrapper is now by using Composer - see examples on wrapper's Github page) May 29, 2016 at 8:11
22

There is the instagram public API's tags section that can help you do this.

5
  • The first URL seems broken. This one works: instagram.com/developer/endpoints/tags
    – Shahar
    Feb 19, 2014 at 21:48
  • 1
    The instagram API just appears insane. Do they really expect you to obtain authentication from every visitor just to get a public feed?
    – Simon E.
    Oct 21, 2014 at 0:07
  • You dont need to authenticate users for such requests. You client id will suffice. Your app will need user authentication if it does something on behalf of user. (commenting, liking, browsing a user’s feed, etc.).
    – Sinan
    Dec 4, 2014 at 23:20
  • @SimonEast the intention is that you don't use the API for these purposes at all. They want you feeding into the ecosystem, not pulling content out of it. Mar 10, 2017 at 9:44
  • Is there any way to get the posts using various hashtags in my android app? Aug 26, 2017 at 5:25
16

If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.

 function callInstagram($url)
    {
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    $tag = 'YOUR_TAG_HERE';
    $client_id = "YOUR_CLIENT_ID";
    $url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;

    $inst_stream = callInstagram($url);
    $results = json_decode($inst_stream, true);

    //Now parse through the $results array to display your results... 
    foreach($results['data'] as $item){
        $image_link = $item['images']['low_resolution']['url'];
        echo '<img src="'.$image_link.'" />';
    }
5
  • I've noticed it grabs only 20 pictures. Are those 20 latest pictures? How to get more?
    – dKab
    Oct 22, 2014 at 18:10
  • Those are the latest 20. If you look at the URL, it has 'media/recent'. According to the Instagram API, that will order by datetime descending.
    – mirichan
    Oct 24, 2014 at 8:12
  • @Gursharan Singh Hello i have hashtag with underscore and i'm using this code and work fine for all hashtag except hashtag with underscore any help.
    – Fadi
    Jan 3, 2016 at 9:32
  • but do you really see all picutres? Im in sandbox mode, i can only see the pictures of the accesstoken-owner? Jan 5, 2016 at 11:30
  • How can I get posts from Instagram in my android app using various hashtags? Aug 28, 2017 at 6:43
14

Since Nov 17, 2015 you have to authenticate users to make any (even such as "get some pictures who have specific hashtag") requests. See the Instagram Platform Changelog:

Apps created on or after Nov 17, 2015: All API endpoints require a valid access_token. Apps created before Nov 17, 2015: Unaffected by new API behavior until June 1, 2016.

this makes now all answers given here before June 1, 2016 no longer useful.

3
8

I have set a php code which can help in case you want to access Instagram images without api on basis of hashtag

Php Code for Instagram hashtag images

3
5

To get more than 20 you can use a load more button.

index.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Instagram more button example</title>
  <!--
    Instagram PHP API class @ Github
    https://github.com/cosenary/Instagram-PHP-API
  -->
  <style>
    article, aside, figure, footer, header, hgroup, 
    menu, nav, section { display: block; }
    ul {
      width: 950px;
    }
    ul > li {
      float: left;
      list-style: none;
      padding: 4px;
    }
    #more {
      bottom: 8px;
      margin-left: 80px;
      position: fixed;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $('#more').click(function() {
        var tag   = $(this).data('tag'),
            maxid = $(this).data('maxid');

        $.ajax({
          type: 'GET',
          url: 'ajax.php',
          data: {
            tag: tag,
            max_id: maxid
          },
          dataType: 'json',
          cache: false,
          success: function(data) {
            // Output data
            $.each(data.images, function(i, src) {
              $('ul#photos').append('<li><img src="' + src + '"></li>');
            });

            // Store new maxid
            $('#more').data('maxid', data.next_id);
          }
        });
      });
    });
  </script>
</head>
<body>

<?php
  /**
   * Instagram PHP API
   */

   require_once 'instagram.class.php';

    // Initialize class with client_id
    // Register at http://instagram.com/developer/ and replace client_id with your own
    $instagram = new Instagram('ENTER CLIENT ID HERE');

    // Get latest photos according to geolocation for Växjö
    // $geo = $instagram->searchMedia(56.8770413, 14.8092744);

    $tag = 'sweden';

    // Get recently tagged media
    $media = $instagram->getTagMedia($tag);

    // Display first results in a <ul>
    echo '<ul id="photos">';

    foreach ($media->data as $data) 
    {
        echo '<li><img src="'.$data->images->thumbnail->url.'"></li>';
    }
    echo '</ul>';

    // Show 'load more' button
    echo '<br><button id="more" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'">Load more ...</button>';
?>

</body>
</html>

ajax.php

<?php
    /**
     * Instagram PHP API
     */

     require_once 'instagram.class.php';

      // Initialize class for public requests
      $instagram = new Instagram('ENTER CLIENT ID HERE');

      // Receive AJAX request and create call object
      $tag = $_GET['tag'];
      $maxID = $_GET['max_id'];
      $clientID = $instagram->getApiKey();

      $call = new stdClass;
      $call->pagination->next_max_id = $maxID;
      $call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";

      // Receive new data
      $media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));

      // Collect everything for json output
      $images = array();
      foreach ($media->data as $data) {
        $images[] = $data->images->thumbnail->url;
      }

      echo json_encode(array(
        'next_id' => $media->pagination->next_max_id,
        'images'  => $images
      ));
?>

instagram.class.php

Find the function getTagMedia() and replace with:

public function getTagMedia($name, $auth=false, $params=null) {
    return $this->_makeCall('tags/' . $name . '/media/recent', $auth, $params);
}
5
  • This works great! +1 If oy uhave time, could you look at a similar problem that I have? stackoverflow.com/questions/17487231/… Jul 5, 2013 at 10:56
  • It seems someone else managed to answer faster so I guess it's solved.
    – kexxcream
    Jul 5, 2013 at 14:07
  • EXACTLY what I was searching for ! Thanks Kexxcream. One problem remaining. The number of pictures displayed change all the time from 13 pictures to 18. How to fix that? And btw, it's strange, the picture size are not the same. Sometimes I see non square images ! But good script! Love it! Thanks kexxcream
    – jhon
    Aug 1, 2013 at 23:00
  • 1
    No need to hack the core. Instead of editing instagram.class.php just set $instagram->setClientID('YOUR_CLIENT_ID'); Mar 9, 2014 at 13:23
  • doesnt work anymore, access_token is also needed. Jan 5, 2016 at 11:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.