Create a Tweet This Button with Shortened URLs

16 Jul 2009 2 Comment

Because micro-blogging services like Twitter have a character limit of 140 characters, it is paramount that you shorten your links as much as possible. WordPress does not do this natively but that does not mean that it is difficult. We can include our code in the functions page for an easy,  repetivitve action. You can see an example of how it looks below this post. Is.gd probably outputs the shortest links, but you can use most other url shortners for this tutorial. Open your templates functions.php and include the following code.

function getTinyUrl($url) {
  $tinyurl = file_get_contents("http://is.gd/api.php?longurl=".$url);
  return $tinyurl;
}

What this code means is that we create new function called “createTinyLink” and allow a parameter of “$url” to be grabbed so it can be convereted into a tinyURL. Then we create a new variable called “$tinylink” and let that equal to the contents of the function on the is.gd website. I got that link from here. But you could also use Bit.ly or Tinyurl just as simply. The code then returns the contents into where we want it displayed.

After this we go into the single.php (or any page) and enter in:

Tweet this

This creates a link that says Tweet this and the url will be a link to Twitter.com that can update your status with Currently Reading : [The title of the post] and the shortened link to the article.

There you have it extremely easy and very cool addition to your blog, without slowing it down with a million plugins.

  • http://www.timmp.co.uk Tim Pennington

    This is a great post and a great piece of PHP.

  • http://www.ailame.com Kedron

    Thanks for posting this! Just what I was looking for!!!