Easily display your last Tweet

I wanted to show my latest tweet on the front page of this site, and although I know there are several plugins which probably could’ve helped me do this, I decided to see how easy the API was to use.

It turned out to be incredibly easy, as long as you have PHP 5.2 or higher, that is.

This is the code:

require_once(ABSPATH . 'wp-includes/class-snoopy.php');
$snoopy = new Snoopy;
$snoopy->fetch("http://twitter.com/statuses/user_timeline/jdevalk.json?count=1");
$twitterdata = json_decode($snoopy->results,true);
echo "<p>\"".$twitterdata[0]["text"]."\"</p>";

As you can see, I use the Snoopy library to fetch the data, as that comes with WordPress by default. Than I decode the JSON results by using the json_decode function. This is the reason you need PHP 5.2 or up, as this was only included with this version of PHP.

Next, we output it. Of course, this is a quick & dirty implementation. If I got dugg now, and 1,000 people a minute came looking at that page, it should have some sort of caching in there. For now though, this is fine as it is!

Update: As Kim noticed in the comments, I’ve added some code to automatically link any @username mentions to those usernames. Replace the last echo line above with this:

$pattern = '/\@([a-zA-Z]+)/';
$replace = '<a href="http://twitter.com/'.strtolower('\1').'">@\1</a>';
$output = preg_replace($pattern,$replace,$twitterdata[0]["text"]);
echo "<p>\"".$output."\"</p>";

You could even decide to add rel="nofollow" the $replace if you don’t want those links to give juice.

Update 2: To make it even more complex, here is the entire code I now use, which excludes replies and caches the Twitter API requests so you won’t overload the API:

require_once(ABSPATH . 'wp-includes/class-snoopy.php');
$tweet   = get_option("lasttweet");
$url  = "http://twitter.com/statuses/user_timeline/jdevalk.json?count=20";
if ($tweet['lastcheck'] < ( mktime() - 60 ) ) {
  $snoopy = new Snoopy;
  $result = $snoopy->fetch($url);
  if ($result) {
    $twitterdata   = json_decode($snoopy->results,true);
    $i = 0;
    while ($twitterdata[$i]['in_reply_to_user_id'] != '') {
      $i++;
    }
    $pattern  = '/\@([a-zA-Z]+)/';
    $replace  = '<a href="http://twitter.com/'.strtolower('\1').'">@\1</a>';
    $output   = preg_replace($pattern,$replace,$twitterdata[$i]["text"]);  
    
    $tweet['lastcheck'] = mktime();
    $tweet['data']    = $output;
    $tweet['rawdata']  = $twitterdata;
    $tweet['followers'] = $twitterdata[0]['user']['followers_count'];
    update_option('lasttweet',$tweet);
  } else {
    echo "Twitter API not responding.";
  }
} else {
  $output = $tweet['data'];
}
echo "<p>\"".$output."\"</p>";[/code]

As you can see it also saves the amount of followers you have into $tweet['followers'], which I then use to display this:

&lt;p&gt;
  &lt;a href=&quot;http://twitter.com/jdevalk&quot;&gt;
    &lt;?=$tweet[&#x27;followers&#x27;]?&gt; followers on Twitter, and you?
  &lt;/a&gt;
&lt;/p&gt;

Update 3: Another fix to automatically make all links clickable, below this line:

$output = preg_replace($pattern,$replace,$twitterdata[$i][&quot;text&quot;]);

Add:

$output = make_clickable($output);

This will use the WordPress internal make_clickable function to make sure that all URL's are clickable.

Enjoy!

Tags: ,


Yoast.com runs on the Genesis Framework

Genesis theme frameworkThe Genesis Framework empowers you to quickly and easily build incredible websites with WordPress. Whether you're a novice or advanced developer, Genesis provides you with the secure and search-engine-optimized foundation that takes WordPress to places you never thought it could go.

Read our Genesis review or get Genesis now!

50 Responses

  1. Manuel MerzBy Manuel Merz on 24 October, 2008

    Wow awesome share here Joost, was just looking for something like that about 3 hours ago, thank you :)

  2. Kim WoodbridgeBy Kim Woodbridge on 24 October, 2008

    Thanks! This is great. I’ve been using twitter tools to do the same thing but would rather not depend on a plugin. Would it be complicated to have it remove any @ replies?

  3. Joost de ValkBy Joost de Valk on 24 October, 2008

    @Kim nope, I’ll be working on that a bit.

  4. Kim WoodbridgeBy Kim Woodbridge on 24 October, 2008

    I’m a total dunce when it comes to these things and generally need exact step-by-step instructions. When I tried this on my own site the @name was not linked nor was the link that I was sharing. I see on your front page that username of the person that you were talking to was linked. Am I missing something completely obvious?

    Also, I have never commented here until today but I want to thank you. I learn so much from your articles and your newsletter.

  5. Joost de ValkBy Joost de Valk on 24 October, 2008

    Glad to be of service Kim, and no you didn’t miss anything, I added some code later on to do that ;) I’ve updated the post to add it :)

  6. Joost de ValkBy Joost de Valk on 24 October, 2008

    Just updated the post with code that excludes replies and caches the requests, so you won’t overload the Twitter API.

  7. Kim WoodbridgeBy Kim Woodbridge on 25 October, 2008

    Thanks so much!! You’re the best :-)

  8. Kim WoodbridgeBy Kim Woodbridge on 25 October, 2008

    Ok – you’re going to think I’m the biggest pest. I can use the original example and change it to link to the username but when I use the full code I get the following error

    Missing argument 1 for Snoopy::fetch(), called in /home/kimwood/public_html/stage/wp-content/themes/kimwoodbridge/header.php on line 73 and defined in /home/kimwood/public_html/stage/wp-includes/class-snoopy.php on line 123

    Thanks!

  9. Anthony ShapleyBy Anthony Shapley on 25 October, 2008

    Hey Kim,

    Joost just missed the variable out the fetch. Change line 6 to:

    $result = $snoopy->fetch($url);

    and that works great for me. Cheers for the code Joost!

  10. champiBy champi on 25 October, 2008

    Thnx for the code. Something to play with.

    Regards

    Champi

  11. Kim WoodbridgeBy Kim Woodbridge on 25 October, 2008

    Thanks Anthony!

    Got it – it’s in the header of my website, if you want to check it out. :-)

  12. Joost de ValkBy Joost de Valk on 25 October, 2008

    Thanks Anthony, updated the post!

    Just installed WP-Syntax too to make the code a bit more readable, but I don’t know yet whether that’s a keeper or not :)

  13. Joost de ValkBy Joost de Valk on 26 October, 2008

    And another small update to the post to reflect another change I made in my own code :)

  14. Nout van DeijckBy Nout van Deijck on 17 May, 2009

    hey joost, this is a great code!
    I’m going to use the code on my new website/blog that I’m working on!
    But I have a few questions about it:
    I want to display the latest 3 (or a variable) tweets, in stead of the latest one.
    Also, it would be great if the code would display the time at which the tweet was tweeted.
    I hope you can help me with these things, because I’m not such a php-knower!…
    again: thanks for the great code!
    Nout

  15. AshBy Ash on 19 May, 2009

    I like this a lot, but is there a way of getting a time stamp of the tweet? and a short URL?

  16. JohnBy John on 26 May, 2009

    Hi. I might’ve missed something but where do you input a Twitter ID or username?

  17. Forex ProtectorsBy Forex Protectors on 27 May, 2009

    Seems like a great plugin, has exactly what I want. But I’m having a hard time getting it to work on my site. Trying to put it in the header directly above the nav bar but when I add it in the header.php, I just get the code to show up on the site. Am I putting it in the wrong file? My site is on WordPress 2.7. Thanks in advance, can’t wait to get it running!

  18. JohnBy John on 10 June, 2009

    How can I get a similar code for a non-Wordpress site? I want to put my latest tweet in the header of my vBulletin forum.

  19. JONxBLAZEBy JONxBLAZE on 21 June, 2009

    Thanks for the code..it works flawlessly on my blog. How can I retrieve the last 5 tweets as oppose to just 1?

    • IljaBy Ilja on 29 June, 2009

      I would love to know that too, poking around at the code now but no succes so far…

  20. MarkusBy Markus on 22 June, 2009

    Add this to parse hashtags:

    $find = "/(^|\s)#(\w*)/i";
    $replace = "$1<a href='http://twitter.com/search?q=$2' rel="nofollow">#$2</a>";
    $output = preg_replace($find, $replace, $output);
    &lt;/pre
  21. RobertBy Robert on 3 July, 2009

    Hello Yoast,
    I integrated your code into the plugin”Pretty Links” (see http://die-truppe.com/jlf for an example). I also tried to make tweet-links clickable by adding $output = make_clickable($output);
    I then tried to add target=”_blank” as with Pretty Links the tweet-URL is opened within a frame:

    $replace = ' href="http://twitter.com/'.strtolower('\1').'" >@\1';

    Unfortunately this code didn´t work; target=”_blank” is not added; instead the link is marked with rel=”nofollow”. Do you have an idea how to make this work?
    Thanks for any help!
    Robert

    • RobertBy Robert on 3 July, 2009

      The code didnt show up correctly, it should be
      $replace = 'href="http://twitter.com/'.strtolower('\1').'">@\1';
      I added xa otherwise the code would be transformed into a link.

      • RobertBy Robert on 3 July, 2009

        I give up – just think about adding target=”_blank” to line 14 ;-)

  22. AlBy Al on 13 July, 2009

    Firstly, to the little knowledge that I have of how you would implement this, I’ve tried everything. I’ve read the entire post & comment for ideas but no luck. I think I’m missing something. My theme has a widget ready header, I would like to display my latest tweet in the header. How do I do just that using this code?! Where/How to place it etc.

    Thanks in advance.

    Al.

  23. Sam LoganBy Sam Logan on 12 August, 2009

    Thanks for the great piece of code, works like a charm.

  24. derpBy derp on 27 August, 2009

    This is great and works, but i have the same problem with this as with every other plugin.

    it only displays the first tweet no matter what I do.

    I assume you just change ?count= to however many tweets you want, but it doesn’t work on my blog, it only shows the first tweet.

  25. YoungBy Young on 24 November, 2009

    Thank you for an awesome code Yoast. I had the same question as Ash about using the timestamp, and had to do a good amount of google research on the twitter API before I found the answer:

    will print the unformatted timestamp. Apparently this doesn’t follow any conventional timestamp formats out there, so I had to PHP substr my way into the formatted (yuck):

    $timestamp = $twitterdata[0]["created_at"];
    $day = substr($timestamp, 0, 3);
    $month = substr($timestamp, 4, 3);
    $date = substr($timestamp, 8, 2);
    $time = substr($timestamp, 11, 8);
    $year = substr($timestamp, 26, 4);
    echo $day.”, “.$month.” “.$date.” “.$year.” at “.$time;

    • YoungBy Young on 24 November, 2009

      Oops, forgot the code tags…

  26. JohnBy John on 28 November, 2009

    This was working fine on the last site I built but on a new site I’m building, I used the same code and I get this error:

    Fatal error: Call to undefined function: json_decode()

    Any ideas?

    • Joost de ValkBy Joost de Valk on 28 November, 2009

      Switch to PHP5 instead of PHP4.

Trackbacks

  1. [...] a blog post to fit my layout.  Also, I’ve added my latest tweet to the top of the blog page, using Joost de Valk’s instructions.  The blog’s not going anywhere that it wasn’t already – I’ll still post full length entries here [...]