Twitter integration redux

Twitter** Note: This hack has subsequently been superceded by a plugin **

Another couple of new tweaks built in to the blog, to make it easy for readers to tweet about a post they are currently reading on the blog, with a handy link included.

Inspired by a very nice article on Wp Recipes (thanks catswhocode) that I found via one of may fave tech online magazines: Smashing Magazine.

The method is simple, the best things always are; generate a tiny url for the current post and attach that to a button that calls Twitter itself, providing it with a pre-compiled tweet.

I amended the original code a little, as you do, building the link in php and then displaying it in an extra span after the date span on each post. Hitting the little Twitter icon beside the date on a post takes you to the twitter page and pre-fills the tweet field with a comment and the tinyurl. Nice.

Want the code?  Well here you go:

First, some CSS jiggery-pokery in style.css to position the icon

.post .tweet {
background:none;
float:left;
}

Next, include the tinyurl generation code in function.php

function getTinyUrl($url) {
$tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
return $tinyurl;
}

Then some code to generate the link – add to index.php (main posts), archive.php (categorised posts) and single.php (single posts).  I put it just after the just after the php call to get ‘the_ID()‘.

$turl=getTinyUrl(get_permalink($post->ID));
$timg='<img title="Tweet this post" src="http://www.bimbogami.co.uk/wp/images/Twitter-16x16.png" alt="Tweet this post" />';
$tweet='<a href="http://twitter.com/home?status=Check%20this%20out:%20'.$turl.'" target="_blank">'.$timg.'</a>';
?&gt;

And finally, stick the following where you want the button to appear. In my case immediately after the post date span in the above three .php files.

Sweet.

Leave a Reply