TroyGrosfield.com TroyGrosfield.com

Headline

Include Images in Your Twitter Widget

Author
by Troy Grosfield
Date
October 13th, 2010
Category
Developer
Story

Update: This script to pull images into the widget no longer works.  Twitter started returning all links including images as a shortened twitter http://t.co url which just redirects to the actual resource.  The bad part about this is you can’t tell if the link is truly an image or not and you can’t reference an image that redirects as an image’s src attribute.

With that said, one possible solution would be to create a resource on your domain to check these shortened urls.  So, for example, I would have a url to check each twitter link’s content type that would be something like:

http://troygrosfield.com/check-twitter-url?u=http://t.co/2HXlnL47

Your server would then make a GET request the twitter shortened url http://t.co/2HXlnL47 to see where the redirect was sent to.  You would read the header “Location” that was returned with the redirect response.  Then make a second request to the redirected url and read the content type.  If it’s an image content type then return that to your ajax request and return the actual image url.

The other solution was so much easier….

END UPDATE

When Twitter turned off basic auth, it left me searching for a new solution to pull my tweets into my site. That’s when I discovered that Twitter already had a widget that would do this for me.  Problem solved right?  Well, not exactly.  There were two problems at hand:

  1. The styling of the tweets didn’t jive well with the rest of my site.  So I needed to override the default styles.
  2. If I had an image in my tweet no preview thumbnail images were available.

I knew I would end up restyling the tweets so when going through the prompts on the twitter widget site I selected as bare bones of a widget I could find. Here was the result:

Tweets without modifications

Tweets without modifications

So, first thing was to reswizzle the styles.

CSS

.twtr-hd { display: none; }
.twtr-timeline {
    height: auto !important;
    overflow: auto !important;
}
.twtr-timeline .twtr-tweet-text .twtr-thumb {
    display: block;
    margin: 10px 5px;
}
.twtr-timeline .twtr-tweet-text .twtr-thumb img {
    border: 2px outset black !important;
    height: 125px;
    width: 125px;
}
.twtr-widget .twtr-tweet {
    border-bottom: 1px solid silver !important;
}

I’m hiding the header, changing the line colors and styles, and making a few other simple mods. You can style the twitter feed however you want. That’s not really the purpose of this post.

Result

Tweets without images

Tweets without images

Ok, great! Now I had my twitter feed in my site with the same look and feel as the rest of my site!

The next issue I had was that no preview images were displayed if I had tweeted about an image. Specifically, images that were from twitpic. So, I thought I’d throw some javascript together and pull the thumnail version of the images into my tweets.

Javascript

I’m using jQuery version 1.4.2. jQuery must be pulled into your site in order to reuse this code.

function getTwitterImages(){
    // Show images for twitter tweets if there are any
    $('.twtr-timeline .twtr-hyperlink').each( function(){
        // All whitelisted domains you want to pull images in from.
        var allowed_domains = ['twitpic.com'];
	var lnk_obj = $(this);
	var orig_url = lnk_obj.html();

        // parse through allowed domains to see if image url domain
        // is whitelisted
	$(allowed_domains).each( function(index, value){
            if (orig_url.indexOf(value) != -1) {
                // twitpic specific parsing to get thumbnails
                if (value == 'twitpic.com') {
                    // get the thumbnail image url
                    var thumb_url = orig_url.replace('.com/','.com/show/thumb/');
                    var img = '<img src="' + thumb_url + '" alt="TwitPic" />';
                    var anchor = '<a class="twtr-thumb" href="' + orig_url +'">' + img + '</a>';
                    // insert the html before the date object
                    $(anchor).insertBefore(lnk_obj.parent().find('em'));
                }
            }
        });
    });
}

Result

Anywhere you see a tweet with a link from the twitpic domain, the script will grab the image thumbnail and display it below the actual tweet and above the date.

Tweets with images

Tweets with images

One thing to note with this solution. The twitter widget loads your tweets using javascript. If your code to pull in tweet images runs before the tweets themselves have been injected into the page then the images won’t get pulled in because the tweet DOM objects don’t exist yet. Here’s one way to fix that:

Ensure the Feed Exists

// Wait until all elements in the page have loaded
$(document).ready( function(){
    // wait until the twitter widget has been loaded on the page
    $('.twtr-widget').ready( function(){
        // wait 500 milliseconds before getting the images.  This
        // ensures the script doesn't run before the links have
        // been fully loaded.
        setTimeout('getTwitterImages()', 500);
    });
});

Full Source

Feel free to use this code in your site!

$(document).ready( function(){
    $('.twtr-widget').ready( function(){
        setTimeout('getTwitterImages()', 500);
    });
});

function getTwitterImages(){
    $('.twtr-timeline .twtr-hyperlink').each( function(){
        var allowed_domains = ['twitpic.com'];
	var lnk_obj = $(this);
	var orig_url = lnk_obj.html();

	$(allowed_domains).each( function(index, value){
            if (orig_url.indexOf(value) != -1) {
                if (value == 'twitpic.com') {
                    var thumb_url = orig_url.replace('.com/','.com/show/thumb/');
                    var img = '<img src="' + thumb_url + '" alt="TwitPic" />';
                    var anchor = '<a class="twtr-thumb" href="' + orig_url +'">' + img + '</a>';
                    $(anchor).insertBefore(lnk_obj.parent().find('em'));
                }
            }
        });
    });
}
Tags
Comments
9 Comments »

9 Comments

Leave a reply

 
  1. Author
    mallorca life
    Date
    January 8th, 2013 at 7:37 am
    Comment

    … [Trackback]…

    […] Read More here: blog.troygrosfield.com/2010/10/13/include-images-in-your-twitter-widget/ […]…

  2. Author
    URL
    Date
    August 21st, 2012 at 10:40 am
    Comment

    … [Trackback]…

    […] Informations on that Topic: blog.troygrosfield.com/2010/10/13/include-images-in-your-twitter-widget/ […]…

  3. Author
    Scott
    Date
    June 22nd, 2012 at 10:26 am
    Comment

    Hi there,

    Great code, thanks!
    As Anthony mentioned, does this still work with the new twitter api? And is there a way to filter tweets that do not have an image attached to them?

    Kind Regards,
    Scott

  4. Author
    Anthony
    Date
    January 25th, 2012 at 11:11 am
    Comment

    Does this still work? It doesnt work for me.

  5. Author
    google
    Date
    August 29th, 2011 at 11:41 am
    Comment

    I liked your article is an interesting technology
    thanks to google I found you

  6. Author
    Fausto
    Date
    June 29th, 2011 at 9:33 am
    Comment

    Thanks a lot for sharing!

  7. Author
    Matt
    Date
    April 15th, 2011 at 8:57 am
    Comment

    That’s not what I asked, and it’s a test page only. I’m using that as a testing grounds to get their widget to show the images before I implement it as a widget in my WordPress install. I just want thumbnails to be displayed instead of the twitpic/yfrog stuff.

  8. Author
    Troy Grosfield
    Date
    April 9th, 2011 at 4:49 pm
    Comment

    When I view the source of your page all I see if three script tags. Read up on how to properly format an html page. w3schools always has some good examples: http://www.w3schools.com/Html/html_examples.asp

  9. Author
    Matt
    Date
    April 8th, 2011 at 6:07 am
    Comment

    I currently have the code given to me from the Twitter Widget page and it produces a nice widget, but I don’t know how to add your code to the mix in order to get it to display the images as thumbnails instead of links. All I really have is an HTML page right now with the Widget code from Twitter inside of it. Nothing else. If you check out this link, http://caching.bobsroom.com/test.php, you’ll see what I produced thus far using their out of the box widget stuff. What I REALLY want is that exact widget, with image thumbnails for twitpic and Yfrog, and I’d like to be able to get rid of the bottom blue twitter line all together, but I’m looking at just the image stuff right now.

    Would you be able to point me in the right direction? Any help would be appreciated. Thanks.