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: https://twitter.com/twitter/status/76360760606986241 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!


Share this post on…

  • Mastodon
  • Facebook
  • LinkedIn
  • BlueSky
  • Threads
  • Reddit
  • HackerNews
  • Lobsters
  • WhatsApp
  • Telegram

3 thoughts on “Displaying Twitter Photos via Entities”

  1. says:

    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).

    Reply

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">