Displaying Twitter Photos via Entities


Twitter has announced that it will soon open up a native photo sharing service.

Rather than using an external service like Embed.ly to retrieve thumbnails, all the data is embedded within Twitter Entities.

So, if you request a status using "include_entities=true", you will be able to grab the image and display the thumbnail using the following code.

function twitter_get_media($status) {
   if($status->entities->media) {

      $url = $status->entities->media[0]->media_url_https;

      $width = $status->entities->media[0]->sizes->thumb->w;
      $height = $status->entities->media[0]->sizes->thumb->h;

      $media_html = "<a href="" . $url . "" target='_blank'>";
      $media_html .=  "<img src="" . $url . ":thumb" width="" . $width . 
         "" height="" . $height . "" />";
      $media_html .= "</a><br />";

      return $media_html;
   }        
}

So, a tweet like this:

Will render like this (in Dabr):
Twitter Dabr Images

Notes

This is very rough and ready proof of concept code. Beware of the following:

  • This will only take the first image from the tweet.
  • Only images are supported - I'm not sure how their proposed video sharing will work.
  • There's no error checking.
  • In the above code, the https URL is used - if you want a non-SSL link, you'll need to remove the "_https"

Enjoy!

3 thoughts on “Displaying Twitter Photos via Entities

  1. function twitter_get_media($status) {
    if($status->entities->media) {
    $media_html = '';
    foreach($status->entities->media as $media) {
          $url = $media->media_url_https;
          $link = $media->url;
     
          $width = $media->sizes->thumb->w;
          $height = $media->sizes->thumb->h;
    
          $media_html .= "<a href="" rel="nofollow">";
          $media_html .=  "";
          $media_html .= "</a>";
    }
    return $media_html;
    }

    Links to the actual tweet/image page and loops through all the images (possibly).

What do you reckon?

%d bloggers like this: