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

Be Sociable, Share!

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: