Grow your CSS skills. Land your dream job.

Last updated on:

Display Last Tweet

The code below no longer works as-is with the Twitter API update to 1.1 as of 2013-06-11. The 1.1 API requires oAuth which requires a server side component. Here's a PHP way to interact with the new API. Googling around will find you many other libraries and such. There is an all-JavaScript method for getting tweets, but it may be a bit of a loophole that you may not want to count on.
$.getJSON("https://api.twitter.com/1/statuses/user_timeline/chriscoyier.json?count=1&include_rts=1&callback=?", function(data) {
     $("#twitter").html(data[0].text);
});

Make sure you change username.json to your actual username and #twitter to the actual selector you wish to replace the contents of.

You can play around with this on this CodePen (deprecated).

Comments

  1. Jamie
    Permalink to comment#

    Love it!

  2. Jamie
    Permalink to comment#

    But how can I show the last several tweets?

  3. Permalink to comment#

    Add this
    callback=twitterCallback2&count=1
    after this callback=?

    Change the 1 to as many as you’d like.

  4. Permalink to comment#

    I tried to use the

    callback=twitterCallback2&count=1

    It doesn’t seem to work for some reason…

    $.getJSON("http://twitter.com/statuses/user_timeline/boombapgr.json?callback=twitterCallback2&count=3", function(data) {
    $("#tweets").html(data[0].text);
    });

    Connecting to Twitter…

  5. Permalink to comment#

    Yeah, similar sort of thing, can get the one on it’s own to work, but no more than that…

  6. For those having an issue with more than one item, it’s because you have to put it inside of an array if it’s more than one item.

    Something like:
    instead of:

    (data){
    
    });

    use

    (data){
     for (i = 0; i < item.length; i++) {
                var each = item[i];
    
     }
    }
  7. Jay

    Will Twitter limit the number of jSON requests my server makes? In other words, if my site gets 1000 hits per hour should i be caching the tweet in a database? Or does twitter see it as the client making the request rather than my web server?

    • This site does OK without it… but… I probably should be caching. Caching something like this is just a good practice period. Regarding the limits, I’m not sure there is on stuff like just pulling from the timeline. I think it’s stuff like search that is limited. Could be wrong though.

    • Giovanni Mattucci
      Permalink to comment#

      There is definitely a limit to the number of request you can make. So storing tweet information (in a database or otherwise) is pretty much a must.

      For an unauthenticated query to twitter, there is a limit of 150 requests per hour.

      You can read all about it in twitters dev. documentation here.

  8. Permalink to comment#

    you can also refer to this site on how to display your latest tweets in twitter. with twitter API.

    http://www.ryscript.co.cc/web/how-to-display-latest-tweets-using-javascript-and-twitter-api/

    thanks..

  9. Nice simple code..
    I gonna use that one..
    Thanks

  10. Permalink to comment#

    It displays anchors as text on my page:

    http://www.eclipse-webdesign.nl/contact

    Any ideas?

  11. Eclipse
    Permalink to comment#

    works… thanks!

  12. If you want to display your tweets with working links/hashtags/usernamelinks you could use this: `

    function parseTweet($text) {
      $pattern_url = '~(?>[a-z+]{2,}://|www\.)(?:[a-z0-9]+(?:\.[a-z0-9]+)?@)?(?:(?:[a-z](?:[a-z0-9]|(?< !-)-)*[a-z0-9])(?:\.[a-z](?:[a-z0-9]|(?\2', $text);
      $tweet = preg_replace('/(^|\s)@(\w+)/', '\1@\2', $tweet);
      $tweet = preg_replace("#(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)#is", "\\1[link]", $tweet);
      return $tweet;
    }

    `

  13. This is awsome, I’ll try to implement this like now!!! :D

  14. This did not work :(

  15. @Daniel & others – Bob Kruithof’s code did not work for the following reasons: He did not replace the html brackets with their ascii counterparts (as it tells you to do below), therefore the links in the code have been displayed as actual links in your browser (as you can see they are rendered in blue & you can click on them…) and He hadn’t escaped some of the quotes in the last preg_replace. The following code works perfectly. Just copy & paste it inside the div on your page where you want your tweet to be displayed, and change ‘YOURNAMEHERE’ to your name.

    < ?php 
      function parseTweet($text) { $pattern\_url = '~(?>\[a-z+]{2,}://|www\.)(?:\[a-z0-9]+(?:\.[a-z0-9]+)?@)?(?:(?:[a-z\](?:\[a-z0-9]|(?< !-)-)\*[a-z0-9])(?:\.[a-z\](?:[a-z0-9]|(?\2', $text); $tweet = preg\_replace('/(^|\s)@(\w+)/', '\1@\2', $tweet); $tweet = preg\_replace("#(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]\*)(/[\w\#$%&~/.\-;:=,?@\[\]+]\*)?)#is", "\\1[link]", $tweet); return $tweet; } $username='YOURNAMEHERE'; // set user name $format='json'; // set format $tweet=json\_decode(file\_get\_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}")); // get tweets and decode them into a variable $theTweet = parseTweet($tweet[0]->text); echo '"' . $theTweet . '"'; 
    ?>
    • Thomas
      Permalink to comment#

      This above code does not work if copy and pasted. The pattern_url variable closes php ‘?>’ which I’m not sure is the intention – if it is than its never reopened which gives you the error. Not sure how to fix as I don’t know how to use patterns and preg functions. Anyone have any ideas?

    • Permalink to comment#

      had the same problem… just replace the all the ‘ and the ” — with ‘ and “…

      works for me…

    • Permalink to comment#

      works for me. thank you

  16. Permalink to comment#

    This is not working in IE at the moment? Any ideas?

    • james
      Permalink to comment#

      Use a modern browser like safari, firefox or chrome and ditch your prehistoric IE.

      IE is like the fat, dumb kid at school that everyone had to wait behind for in every class and carry on their backs in all the sports.

  17. Works fine for me!!

    don’t forget to include jQuery library! lol

  18. Rob
    Permalink to comment#

    RJ, use the code that Inigo posted. Just make sure to change all of the quotes as they get messed up formatting if pasted into certain text editors. It works fine in all current versions of IE, Chrome, Firefox, and Opera…

  19. Permalink to comment#

    How do I exclude links from tweets returned? I do not want any tweets with links coming in. I know there is a filter:links paramater but not sure how to implement.

  20. Howdy
    Permalink to comment#

    Any idea why this works with all my twitter usernames except the one below?

  21. Permalink to comment#

    Doesn’t work after retweet.

  22. How do I make random tweets?

  23. Marina Bearman
    Permalink to comment#

    To display last five tweets using jQuery:

    $.getJSON(“http://twitter.com/statuses/user_timeline/NoReservations.json?callback=?&count=6″, function(data) {
    /* $(“#twitter”).html(data[0].text);*/
    $.each(data, function(i, object) {

    $(“#twitter”).append(”+object.text+”);

    });

    });

  24. this works for me, for several tweets (5 in this case) with links.

    http://jsfiddle.net/8jmLY/664/

  25. if I’m not late for this party, this seems to work for me though. using jquery framework, put this in you html/php page and create as and inside it put this code. change the username to yours.

    $(document).ready(function() {
    
      var tweets = 3; //specify the number you want here
    
      $.ajax({
    
        url: “http://twitter.com/statuses/user_timeline/krialex21.json?&count=” + tweets +”&callback=?”,
        dataType: “json”,
        timeout: 15000,
    
        success: function(data) {
          for (i=0; i<data.length; i++) {
            $("#twitter").append("” + data[i].text);
            $(“#twitter”).append(“” + data[i].created_at +”");
          }
        },
    
        error: function() {
          alert(“Failure!”);
        }
    
      });
    
    });
    
  26. Permalink to comment#

    So, followed this (and the latest comments), and no problem pulling the latest tweet at all. Easy as pie, actually. Terrific.

    Looking through the json data pulled from Twitter, I really want to pull the “statuses_count” – i.e., the number of tweets you’ve posted. It’s displayed several times here: https://twitter.com/statuses/user_timeline/kyle_conrad.json?callback=? as well as here: https://api.twitter.com/1/users/show.json?screen_name=kyle_conrad&include_entities=true (and outlined here: https://dev.twitter.com/docs/api ).

    However, I can’t seem to pull that – pulling text is no problem, but any of the other JSON data that I want to pull just returns an “undefined.” There has to be something simple that I’m doing wrong, right?

  27. Hello everyone,

    I was wondering, how do I display the lastest tweet in one div. Then the 2nd tweet in another div and then the 3rd tweet in another div. Something along the lines of this:

    (div)lastest tweet(/div)
    (div)random picture(/div)
    (div)random picture(/div)
    (div)2nd tweet(/div)
    (div)random article(/div)
    (div)random picture(/div)
    (div)third tweet(/div)

    how would i go about that? I’m still looking but I dont even know the terminology to even search. Aggregate?

    Thanks.

  28. Miles
    Permalink to comment#

    hi was just wondering what i need to input to have the time of tweet showed e.g. 17 Mins ago , 1 hr ago etc

    • Giovanni Mattucci
      Permalink to comment#

      Here is an article that shows you how to use javascript to do what you want. Basically, in the returned JSON information there is a variable called “created__at.”

      You basically have to write your own math to figure out from the created_at timestamp into a “1 hour ago” sort of information.

      Also you might want to delve into Twitters API documentation: https://dev.twitter.com

  29. Oumz
    Permalink to comment#

    This no longer works, there seems to be some update by twitter recently …
    It used to work fine but now I get this error : Sorry, that page does not exist”,”code”:34

    Any workaround or quickfixes to this??

  30. Permalink to comment#

    I’m agree, #Oumz, this doesn’t work since yesterday!

  31. Charles
    Permalink to comment#

    I also agree with #Oumz. I can’t get any scripts to work.

  32. Permalink to comment#

    Thanks for the interesting post, I was using the old simple two lines of code below like many other people but
    now it seems Twitter has prohibited this and we are all left with empty areas. Is there any way around this or do we really have to put up with the ugly widgets??

  33. Permalink to comment#

    Sorry, it didn’t post.

    src=”http://twitter.com/javascripts/blogger.js”>

    src=”http://twitter.com/statuses/user_timeline/username.json?callback=twitterCallback2&count=2″>

  34. Works like a charm! Thanks!

  35. Aniket Betkikar
    Permalink to comment#

    Worked like a charm!!!! :) Thank you.

  36. Permalink to comment#

    how can I use it on html?

  37. Jeff
    Permalink to comment#

    Hi does anyone have a fix so the tweets will display with clickable links? I’ve been trying to get the following to work with no luck

    function twitterCallback2(twitters) {
    var statusHTML = [];
    for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh):\/\/[^”\s\<>]*[^.,;'”>:\s\<>)]!])/g, function(url) {
    return ‘‘+url+’‘;
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
    return reply.charAt(0)+’‘+reply.substring(1)+’‘;
    });
    statusHTML.push(‘

    “’+status+’” – ‘+relative_time(twitters[i].created_at)+’

    ‘);
    }

    $(‘.loading’).fadeOut(750, function() {
    $(‘#latest_tweet’).append($(statusHTML.join(”)).hide().fadeIn(750));
    });

    }

  38. Ivana
    Permalink to comment#

    Hiya, I’m just wondering if there’s a way to add the time to this, as well as the username. e.g., “12:22 by @username”

    Thanks !

  39. David F
    Permalink to comment#

    I’m trying to add this to my site, but it doesn’t seem to be working, I’m relatively new to web development and I’m sure its a simple oversight on my part but how should I connect the js file to my html file?

  40. Kevin
    Permalink to comment#

    It’s not as easy to implement as Chris’s code up above but I found the MiniTwitter jQuery plugin that allows for the ability to be style in css. Very clean & so far is reliable.

  41. Dave
    Permalink to comment#

    Can I specify a hashtag so that it brings back the latest tweet with a particular hashtag in?

  42. Permalink to comment#

    Thanks for this!

    Anyway how can I get the date of the tweet when it has been posted?

    Best,
    John

  43. Just wondering if this means I’ll have to use the widget eventually instead of this? Because I really like Chris’ solution! A widget will be nowhere near as elegant I assure you

    Regards,
    Scott

  44. Mike
    Permalink to comment#

    Exactly what I was looking for – simple and elegant code. Cheers.

  45. @Aron Duby

    Unfortunately you’re completely correct. I went to knock up a quick splash page for a client today using this code, as i’ve done since Mr Coyier originally posted it, and i found it no longer works.

    Time to hunt down an adequate solution as nothing Twitter provides is half as good for use.

  46. A lot of people have ben asking how to convert the text urls to actual urls

    function url2Links(text) {
      var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~<em>|!:,.;]*[-A-Z0-9+&@#\/%=~</em>|])/ig;
      return text.replace(exp,"<a href='$1' rel="nofollow">$1</a>"); 
    }
    
  47. I’m planning on using this on my blog soon. Thanks! :)

  48. No, it doesn’t displaying my tweets. Please help. I think Twitter updated the API.

    Please update the post.

  49. Using a few of the comments previously posted here, I have created a handy snippet for anyone to use. All that’s needed is the twitter handle. It can be easily amended to display multiple previous tweets, and not just the most recent.

    Enjoy!

    /**
     * Get latest tweet via Twitter API, in JSON format,
     * 
     * Format tweet with working URLs for urls, hashtags, and mentions
     * 
     * @param $user
     */
    $user = 'PierceComms'; // case in-sensitive
    
    $json_results = json_decode( file_get_contents( 'https://api.twitter.com/1/statuses/user_timeline/'.$user.'.json?count=1&include_rts=1&callback=?' ) );
    $tweet = $json_results[0]->text;
    
    $pattern_hashtag = '/#([\\d\\w]+)/';
    $replace_hashtag = '<a href="http://twitter.com/#search?q=%23$1" target="_blank">$0</a>';
    
    $pattern_mention = '#@([\\d\\w]+)#';
    $replace_mention = '<a href="http://twitter.com/$1" target="_blank">$0</a>';
    
    $pattern_url = '/http:\/\/([a-z0-9_\.\-\+\&\!\#\~\/\,]+)/i';
    $replace_url = '<a href="http://$1" target="_blank">http://$1</a>';
    
    // Replace http://url.com with working URL
    // URLs MUST BE REPLACED FIRST
    $tweet = preg_replace( $pattern_url, $replace_url, $tweet );
    // Replace #hashtags with working URL
    $tweet = preg_replace( $pattern_hashtag, $replace_hashtag, $tweet );
    // Replace @mentions with working URL
    $tweet = preg_replace( $pattern_mention, $replace_mention, $tweet );
    
    echo $tweet;
    
  50. carlos
    Permalink to comment#

    how can i display the fotmat-less last tweet with this new api version?

  51. This doesn’t seems to work now, please update this article. Thank you.

  52. m

    what r d things should i install before fetching the tweets? what r the softwares i required for this i dont know.please help me for this. i want the code for search the twitters ……

  53. Eugene

    Hi,

    Not working anymore.

  54. This is when technology becomes a pain in the ***.
    I really hate having to go back and change things like these just because Twitter decided to make changes.

  55. radhika
    Permalink to comment#

    I want to display the post time like about 19 hours ago.how do i do?

  56. Dev Meghraj
    Permalink to comment#

    Hi can you update this post for twitter api changes.

    https://dev.twitter.com/docs/api/1.1/overview

  57. FYI This is out of date now

  58. Permalink to comment#

    Is there a way to display the tweet count for a particular post like the way jetpack plugin does?

  59. Charles
    Permalink to comment#

    We can use Ruby to get the latest tweet:

    require "rubygems"
    require "nokogiri"
    require "open-uri"
    
    doc = Nokogiri::HTML(open("https://twitter.com/<screenname>"))
    doc.at_css(".expanding-stream-item .tweet-text").text
    
  60. Error message :
    The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.

    according to the documentation of twitter api,
    API v1.1 is released, user authorization (and access tokens) are required for all API 1.1 requests. In the weeks following release, some methods will require only application-based authentication for certain “userless” contexts.

  61. thanks you for your code, you helped me!

  62. Shahjehan

    I like This Example Which is well work for me

    http://codepen.io/jasonmayes/pen/Ioype

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".