Tuesday, December 22, 2009
No-Plugin Twitter + WordPress

While one of the greatest strengths of WordPress as a web design tool is the wide range of open-source plug-ins it offers, I often find them quite difficult to customize. So when I wanted to link my Twitter to this website, I searched for a way to do it without plug-ins. I found a beautiful snippet of back-end code at yoast.com that allows me to access the Twitter API, snag the latest entry, and return an array containing its attributes. God bless yoast. I hope he doesn’t mind me posting this here.

The code uses PHP and its Snoopy object to crack into the API using JSON:

1
2
3
4
5
6
7
8
9
10
11
<?php
require_once(ABSPATH . 'wp-includes/class-snoopy.php');
$snoopy = new Snoopy;
$snoopy->fetch("http://twitter.com/statuses/user_timeline/ysquared86.json?count=1");
$twitterdata = json_decode($snoopy->results,true);
$pattern = '/\@([a-zA-Z]+)/';
$replace = '<a href="http://twitter.com/'.strtolower('\1').'">@\1</a>';
$output = preg_replace($pattern,$replace,$twitterdata[0]["text"]);
$output = make_clickable($output);
echo "\"".$output."\"";
?>

Line 2 and 3 includes the Snoopy files and creates a new Snoopy object to fetch your data. Line 4 specifies the location of the data. ysquared86 is my Twitter username – replace it with yours. The ?count=1 grabs the latest tweet. Line 5 decodes the data using JSON and creates an array named $twitterdata. Lines 6 through 8 finds any other usernames in the entries and creates a link to their twitter page (e.g. @ysquared86). Line 9 uses WordPress’ make_clickable function to retain any links, and Line 10 finally prints the entry onto the page.

Another important attribute you might want to display is the timestamp, but yoast did not cover the topic in his entry, and I had to do an extensive google search to figure it out on my own. Most WP plug-ins for Twitter do this successfully, but again, I’d rather know what my code is doing. It took me forever to find that, as the $twitterdata[0]["text"] was the body of the twitter entry, “created_at” returns the timestamp attribute. However, it turns out, this timestamp does not follow any conventional format, which meant I had to use PHP’s substr function to make it look nice:

1
2
3
4
5
6
7
8
9
<?php
$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 "Posted at ".$time." on ".$day.", ".$month." ".$date." ".$year;                       
?>

So there it is. I wanted to be able to CSS my way around the positioning, and having these PHP chops worked perfectly.

One Response to “No-Plugin Twitter + WordPress”

  1. Hi, Thank you! I would now go on this blog every day!
    Dolly

Leave a Reply

« »