Really Simple Tweet Gathering (with a few bonuses)
This post was written by derek on September 10th, 2008. Filed under PHP, Plugin, Widget, Wordpress, coding, introducing
Update:
I just realized that for some reason the wp-syntax plugin has converted a bunch of my characters to their HTML equivalents. I will go through and try to fix that later. For now, take it with a grain of salt. I will upload the file later and put a <link here>. Thanks and Enjoy!
Preface:
I wrote this simple script / plugin so that I could get my latest tweet from twitter to display on my blog (right over there → in the sidebar). I know, I know, there are plenty of prepackaged and readily available plugins for twitter on wordpress in the wild, but none of them did things the way I wanted them to be done. Some allowed you to tweet directly from you blog, I don’t want that. So were quite intrusive and bore quite the burden on the page loading, you couldn’t possibly want that. The best one I found was a plugin called Simple Twitter, and as the name so succinctly states, it’s incrediby simple. I found this one to be nearly what I wanted, which is why I used it as a “jumping off point” for the script I’m presenting here, but it lacked a couple of key functionalities that I wanted.
- I wanted just my tweet to be displayed
- I wanted only regular tweets, not @replies, to come through
- I wanted links to be actually clickable (really the only point of a link)
- I wanted other twitter usernames to link to their respective twitter pages
Through a little ingenuity and a couple hours of time I have come up with this solution. I present to you, sTwitter. Let me walk you through it!
Code Rundown
I chose to wrap this script in a class for extensibility’s sake and ease of use. My implementation on my website simply includes this file and these first 3 lines create a new instance of the class, sets a variable, and then calls the function that runs the show. At the end of it’s execution the code will echo or print out the tweet, I simply wrapped this include in a paragraph (<p>) tag and then formatted that in CSS to display my tweet as I see fit.
$t = new stwitter(); $t->last = 1; $t->get_twitter_msg(); class stwitter { public $page; public $last; public $msg;
This first section is essentially the ‘main’ function of the script, it’s the one called by whatever it is you choose to have call it, so that the tweet can be returned. It in turn calls the functions necessary to get that done.
// Returns the stored message function get_twitter_msg() { //get the next message from your twitter rss feed $msg = $this->update_twitter_message(); //check to see if it is an @ reply - I didn't want to display //@ replies so if you do, remove this check. if($msg[0] == '@'){ unset($msg); $this->get_twitter_msg(); } //This is the bit of logic that changes things into appropriate links //first we 'explode' the message by the spaces, this puts each word //or group of characters into an array, see php.net/explode $msg_chunks = explode(" ", $msg); //now I parse through that array and examine each of the 'words' foreach($msg_chunks as $chunk){ //is this a twitter username? if it starts with '@' //and is longer than 1 character I make it link to that //user's twitter page if($chunk[0] == '@' && strlen($chunk) > 1){ $out_msg .= ' <a href="http://twitter.com/' . substr($chunk, 1) . '">' . $chunk . '</a> '; } //is this a link? Does it contain 'http://' in the string? //if so, I make it into an actual clickable link to that page elseif(strstr($chunk, 'http://')){ $out_msg .= ' <a href="' . $chunk . '">' . $chunk . '</a> '; } //if you make it this far you're probably just a 'word' else{ $out_msg .= " " . $chunk; } } //'print' out the tweet echo $out_msg; //unset all the variables, this is needed due to the recursion of this function //and it's good practice, don't leave those remnants behind unset($out_msg); unset($this->page); unset($this->last); }
The update_twitter_message function takes the username for the twitter account that you’re trying to gather tweets from and uses it to concatenate the correct URL for that user’s RSS feed. It then calls the function to get the tweet and also the function that strips off the username (which is included in the returned string). Then the tweet is returned up to the fuction above.
// Updates the message cache function update_twitter_message() { // Update cache $twitterId = 'theunlivedlife'; //this is where your Twitter ID should go //make sure that there is a twitter id that is not 'null' if ($twitterId != '') { //$url is the link to the user's public rss feed $url = 'http://twitter.com/statuses/user_timeline/'.$twitterId.'.rss'; //fetch the next tweet from this rss feed $title = $this->get_message_from_url($url); //if it finds a title in the feed if ($title != '') { //chop off the username from the beginning of the string $msg = $this->extract_message_from_twitter_title($title); return $msg; } } }
This is a pretty self explanatory function, strips off the Username.
// Message comes in the format 'Name : Message'. This removes the 'Name : ' part function extract_message_from_twitter_title($title) { $msg = substr($title, strpos($title, ':') + 2); return $msg; }
This function iterates through the ‘page’ which on the first run through, is all of the user’s latest tweets. However, on each execution of this function that page gets trimmed down, one tweet at a time, until we arrive at the latest tweet that is not an @ reply.
// Gets the RSS feed and handles its business function get_message_from_url($url, $tag = 'title', $item = 'item') { $msg = ''; if(!isset($this->page)){ $this->get_page($url); } if ($this->page == '') { return ''; } //behind the scenes is an xml-like data set, this sets what tags to be //looking for when parsing through the data on the feed $itemTag = "<$item>"; $startTag = "<$tag>"; $endTag = "</$tag>"; //this was a hack, changed from Simple Twitter, since I'm iterating //through the feed to find the latest non @ reply I'm doing things //a bit differently, see below - will be changed in future $inItem = true; //this was used before, but then I found a different way around //will change in the future $offset = $this->last; //calls a function that can find the nth position of a string in a string $titlePos = $this->strposOffset($itemTag, $this->page, $offset); //truncate the page data to 6 characters after the found string start //this makes sure that next time we iterate through, if this was an //@ reply, that we skip over it, because the tag we searched for is gone $this->page = substr($this->page, $titlePos + 6); //break up the page into lines in an array $lines = explode("\n",$this->page); //parse through the array to find the actual tweet foreach ($lines as $s) { $s = rtrim($s); //not needed anymore, will be removed in next revision if (strpos($s, $itemTag)) { $inItem = true; } //condition unnecessary, will be removed in next revision if ($inItem) { $msg .= $s; } //did we locate the start and end of the tag in question? //if so, strip out the tweet and save it to $msg if ($inItem && strpos($s, $endTag)) { $msg = substr_replace($msg, '', strpos($msg, $endTag)); $msg = substr($msg, strpos($msg, $startTag) + strlen($startTag)); break; //hop out of the for each since we're done } } //return the tweet to the calling function return $msg; }
This function merely gets the page of data from the user’s twitter RSS feed and sets it as a public class variable. This way all members can interact with it and the script won’t cause you to burn through the 100 requests per hour cap that twitter has enforced.
//Using the PHP Client URL functions, fetch the rss feed for a particular //twitter user account function get_page($url){ $this->page = ''; if (function_exists('curl_init')) { $curl_session = curl_init($url); curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_session, CURLOPT_CONNECTTIMEOUT, 4); curl_setopt($curl_session, CURLOPT_TIMEOUT, 8); $this->page = curl_exec($curl_session); curl_close($curl_session); } }
Wrap Up:
This was a fun little project and I think it might have legs. You’ll have to be the judge of that. I have plans to turn it into an actual Wordpress Plugin and make the ‘bonuses’ that I spoke of optional / configurable.
What do you see as a benefit to widgets or addons like this?
- « Previous: From the Ashes
- Next: TweetFeed Plugin Released »





