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.

  1. function twitter_get_media($status) {
  2.    if($status->entities->media) {
  3.  
  4.       $url = $status->entities->media[0]->media_url_https;
  5.  
  6.       $width = $status->entities->media[0]->sizes->thumb->w;
  7.       $height = $status->entities->media[0]->sizes->thumb->h;
  8.  
  9.       $media_html = "<a href=\"" . $url . "\" target='_blank'>";
  10.       $media_html .=  "<img src=\"" . $url . ":thumb\" width=\"" . $width .
  11.          "\" height=\"" . $height . "\" />";
  12.       $media_html .= "</a><br />";
  13.      
  14.       return $media_html;
  15.    }        
  16. }

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 comments

  1. Ryan Cullen
    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?