Hello there. I am Terry and I am a full-time undergraduate based in Singapore. I take photos, write a blog and design websites.

And no, I'm not a teddy bear.

Displaying your latest tweet on WP, sans plugins

If you haven’t heard of Twitter, stop everything you’re doing right now and be a monk. You’re a WordPress user and you have a Twitter account – the next step you would want to do is to integrate your Twitter feed to your blog, right? There are a whole lot of ways to do so – with the help of plugins and without any. In the past, I’ve used a couple of plugins to get this done – namely Twitter Tools and SimpleTwitter. There is also this top 10 WP plugins list catered for the average WP-Twitter user. A few more that missed the list include WP to Twitter, TwitterPress and Tweetable.

Twitter has also released HTML and Flash widgets to display your tweets – check the links out on how to implement them on your blog. For people who prefer to style things their own way and don’t want the widgets to mess up the “overall harmony” of your design, the best way is to hardcode a PHP command into your theme file to fetch your latest tweet. This will be elabourated upon as we move along.

Whoa, an avalanche of tutorials!

Then we have guides and tutorials written by helpful and brilliant people who are familiar with how PHP works and how to parse feeds and make good use of the Twitter API. We have an excellent tutorial written by Jeff at Perishable Press on how to display your tweets on your WP blog, as well as a tutorial on how to display your tweets easily by Joost de Valk on Yoast. Lorelle gave a comprehensive list on available Twitter plugins, and she loves Twitter Tools to bits. Ryan Barr also posted an elegant way to parse your Twitter feed using PHP only.

Without plugins. Making it lighter.

Shortlisted from the paragraph above, there are two ways to display your latest tweet without needing to download and activate any plugins. Of course, you don’t have to be a PHP guru (I’m neither one) to get it done with – just follow the steps and you’ll be good, although it will be very helpful if you have some prior knowledge on any programming languages (PHP and C++ are quite similar in certain ways).

In this tutorial, I will be highlighting the tutorial by Joost, and will be making some improvements on the code. Special thanks to Joost for allowing me to post this tutorial and share my modifications, and not to forget him for writing the code at the first place. Being very illiterate at PHP – I know if, else, elseif, while, for loops and etc, but if you ask me to write something out of them I can’t – his tutorial is a great help to get the basics right.

What I really love about Joost’s method is that it is clean, simple and not too complicated. It doesn’t rely on any plugins and lives right off the class-snoopy.php file that is already present in your WP installation. He also uses the code to exclude any replies (but not excluding retweets), as well as set a time limit so that it doesn’t screams too often at the Twitter API to get your latest tweet.

Combining all his modifications and updates to the original code, we have the following lines:

<?php
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"]);
    $output = make_clickable($output);

    $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>";
?>

Very neat code, short and sweet. There are some improvements that can be made though:

  • It is not immediately obvious where should you place your Twitter username (if you’ve spotted it, you have eagle eyes!)
  • Improve the code so that it recognizes virtually all Twitter usernames
  • Linking up the hashtags, if present, in your tweets to Twitter Search

So here is how we get these done:

1. Insert your Twitter ID/username

Find this expression:

$url  = "http://twitter.com/statuses/user_timeline/jdevalk.json?count=20";

Joost’s Twitter ID is ‘jdevalk’ and you can replace it with your Twitter ID, or someone else’s who you’d want to spy on.

As simple as it gets, here’s the modified version:

$url  = "http://twitter.com/statuses/user_timeline/[insert Twitter ID].json?count=20";

2. Make sure that the code recognizes every imaginable username

This is where it gets a little harder – you will need to do a short read up on regular expressions. Here’s a comprehensive list for you to refer to, and there’s even a handy Wikipedia page for examples and usage of regular expressions. If in doubt, refer to the two pages that I’ve recommended – they would answer 90% of your questions.

Locate this line:

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

The line means that we create a variable named “pattern”, and then make it recognize the character “@” (matched by \@ in regex). Beyond the “@” character, any alphabet, regardless of whether is it upper or lowercase, is recognized. However, here’s a problem: what if the user has a digit, a dash or an underscore?. It won’t be recognized and be assigned to $pattern. Let’s see how we can improve upon it.

There is a regex called \w – it matches all alphabets (upper and lowercase), all digits, the dash and the underscore. You think it’s going to get complicated? No. We want to assign a unique name for the variable as well – so we’ll use “pattern_username” instead, as we will be doing more replacements later.

The + expression means that the preceding expression can be matched more than one time – if you leave it out, the PHP will only match those with single character username. Noooooo!

The preg_replace command makes sure that the $pattern is replaced by whatever is inside $replace. Do note that for $pattern, you have to escape certain characters by using \[character] (single quote + [character]) and not the [character] alone. Escape characters tells preg_replace to read the character behind the backslash literally, and not misinterpret it as something else. Examples:

  • @ will cause problems. Use \@ to escape the @ character.
  • Don’t use #. Use \# instead.
  • Other not relevant, but useful examples:
  • Don’t use .. Use \. instead – reads period literally
  • Don’t use '. Use \' instead – reads single quote literally
  • Don’t use ". Use \" instead – reads double quote literally
  • Don’t use $. Use \$ instead – reads the currency sign literally
  • Don’t use \. Use \\ instead – reads backslash literally

Replace with this:

$pattern_username = '/\@(\w+)/';
$replace_username = '<a href="http://twitter.com/'.strtolower('\1').'" title="\1 at Twitter">@\1</a>';
$output = preg_replace($pattern_username,$replace_username,$twitterdata[$i]["text"]);

An example: “RT @teddyrised This is Sparta! #300movie” will be replaced with a clickable link, “RT @teddyrised This is Sparta! #300movie“.

3. Linking hashtags in your tweet

From the example above, I have added the “300movie” hashtag to my tweet as well. How should I replace the plain text hashtag into a URL? If you’re thinking, you’ll have the rough idea of replicating the code in the previous section and modifying it to your liking. Eureka!

We will add the codes before the following line,

$output = make_clickable($output);

Add the following code:

$pattern_hashtag = '/\#(\w+)/';
$replace_hashtag = '<a href="http://search.twitter.com/search?q=\1" title="Search Twitter for \1">#\1</a>';
$output = preg_replace($pattern_hashtag,$replace_hashtag,$output);

Basically, the same reasoning takes place: we use \# to match the hash character, and the \w+ expression is used to match any character of any length (uninterrupted by space). For this replacement, we will be using the variables $pattern_hashtag and $replace_hashtag for convenience.

An example: “RT @teddyrised This is Sparta! #300movie” will be replaced with a clickable hashtag that brings you to twitter search: “RT @teddyrised This is Sparta! #300movie“.

Done! Here’s the final code

<?php
require_once(ABSPATH . 'wp-includes/class-snoopy.php');
$tweet = get_option("lasttweet");
$url = "http://twitter.com/statuses/user_timeline/[insert Twitter ID].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++;
    }

    /* Replaces username with clickable link */
    $pattern_username = '/\@(\w+)/';
    $replace_username = '<a href="http://twitter.com/'.strtolower('\1').'">@\1</a>';
    $output = preg_replace($pattern_username,$replace_username,$twitterdata[$i]["text"]);

    /* Replaces hashtag with clickable link */
    $pattern_hashtag = '/\#(\w+)/';
    $replace_hashtag = '<a href="http://search.twitter.com/search?q=\1" title="Search Twitter for \1">#\1</a>';
    $output = preg_replace($pattern_hashtag,$replace_hashtag,$output);

    /* Uses internal WP command make_clickable to replace URLs with clickable link */
    $output = make_clickable($output);

    $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>";
?>

That’s all for this tutorial! Should you have any questions, don’t hesitate – just post a comment and ask :)

Burn after reading » Now you're done reading. What's next?

Related

Related posts that might interest you:

Popular

Posts that are popular among visitors:

Share it

If you've enjoyed the post, or think that it might be useful to others, do share in on a social network site that you're using. Thank you!

  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • LinkedIn
  • Reddit
  • Design Float
  • Identi.ca
  • Live
  • Ping.fm
  • Print this article!
  • Twitter
  • Netvibes
  • HackerNews
  • Slashdot

12 responses to “Displaying your latest tweet on WP, sans plugins” » Leave a response

  1. AkiResponse

    Nice tutorial :D As for me, since I no longer use WordPress, I’ve been using lastRSS to parse my feeds :D (that is, on my future CMS)

    Well, another alternative to getting the latest tweet is through Javascript :) It’s most convenient when all the tweets are in a ordered/unordered list and if people are really lazy :)

    Check out Aki’s latest blog post » Discrepancy

  2. GzhangResponse

    Hey, dropping by as I said I will earlier =)

    Keep up the Photoshop tuts. Good stuff.

    Check out Gzhang’s latest blog post » Near Adonis emulation

  3. med

    hehe….i have not joined the tweetering bandwagon yet ;)

  4. Jeff StarrResponse

    Excellent tutorial, Teddy! I am honored to be mentioned alongside the incredible Mr. Joost. Glad to have written that post! This article is perfect example of a well-written, easy-to-follow tutorial, and I am sure it will help lots of folks display their tweets on their sites. Many thanks for sharing this information with us — I am bookmarking it at Delicious right now! :)
    Regards,
    Jeff

    Check out Jeff Starr’s latest blog post » Secure Visitor Posting for WordPress

  5. John SchusterResponse

    I stumbled across your site today while looking through the Hybrid Showcase, and I was so impressed by your child theme!
    About the code, I have a question:
    I’m new to the Hybrid Framework and just finished my first child theme but I’m not quite sure where to put this code. Should I put it in the original Hybrid hooks_actions.php, or should I make a custom functions file and place that in my child themes folder?

    I look forward to your response as this is exactly what I was looking for! Thanks!

  6. rysResponse

    you can refer to this site on how to show the latest tweets in your blog site. as easy as 1 2 3

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

    thanks

  7. simarjeet singhResponse

    hi

    thanks for this script

    working very well,

    but i have a question?

    is there any limit to access data my mean to hit a URL .

    is there any limit to hit a URL on twitter in one day or month.

    hope u can understand what i am asking you.
    thanks

  8. alcoholism detoxResponse

    I’ve read a few just right stuff here. Definitely
    value bookmarking for revisiting. I wonder how much attempt you
    set to make this kind of fantastic informative web site.

Leave a Response » Share your thoughts or Return to top

Your name is required. Why?

  • So that I can address you personally (which I'm more than happy to do).
  • Everyone loves their name to be called, right? Nobody wants to be referred to as 'a certain someone' or Mr X (X-Men members aside).
  • If your post too much spam, your name will be imprinted on a personalised voodoo doll, completely free of charge. I'm just joking!

Your email is needed. Why?

  • Your email is, and will, never be given out to any third party under any conditions (except for people sneaking up behind me when I'm on WP admin).
  • So that I can contact you personally in case of certain issues that I wish to address personally.
  • If you post too much spam, I'll email the same spam you've posted 10 times back to you, completely free of charge.

You can always leave a personal URL behind

  • It can be anything - most people put their blog URL, their facebook page, their Twitter URL, their MySpace or etc.
  • I give love back by saying NO to no-follow. All of your webbie links are dofollows instead.

Twitter. Twitter. Twitter.

  • What is Twitter?: Twitter is a social networking and micro-blogging service that enables its users to send and read other users' updates known as tweets. Tweets are text-based posts of up to 140 bytes in length.
  • What is my Twitter ID?: To get a Twitter ID, you simply have to sign up for an account at Twitter.com. Your ID will be in the format of your profile's URL - http://twitter.com/[userid].

Comment notes

  • Gravatar: You can register for one at Gravatar.com
  • XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">
  • Codes: Wrap them up with <code></code> tags.

Hello Easter Egg hunter! You've discovered the magic of the Konami Code!

Yea. You probably know what the Konami code is before getting to this page. So now what? Here is a randomised YouTube video on my favourites list... which includes Rickroll, if you're luck enough to get it.

You are currently watching Sudden tornado invates soccer match. Loving it? You can even watch the video in its full screen glory :)

The Konami Code:
Konami Code sequence