Shortening URLs with Twitter Tools

Posted in: Web Development, WordPress

I use a great WordPress plugin called Twitter Tools to update my Twitter status with posts from my blog. It’s a great way to get the word out about new content on your site. The only thing that the Twitter Tools doesn’t do automatically is shorten your urls to make it easier to fit in the 140 character limit of Twitter. Fortunately, the author of Twitter Tools did think of this and built in a way for us to do it fairly easily.

Here’s the code that makes it happen:

function get_tinyurl($long_url){
    $ch = curl_init();
    $timeout = 10;
    curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$long_url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    $newurl = curl_exec($ch);
    curl_close($ch);
    return $newurl;
}

add_filter('tweet_blog_post_url', 'get_tinyurl');

Add the above code to your theme’s functions.php file and when you make a new post to your WordPress blog Twitter Tools will update your Twitter status. The tweet will look something like this:

twitterusername New blog post: Your blog post title http://tinyurl.com/xxxxx

That’s it! Pretty simple and straight forward. The function contacts tinyurl.com and returns the shortened url which is then included in your tweet. This works well with TinyURL but I am sure that it can work with other url shortening services as well, as long as they have a similar way to shorten urls. It could be as simple as getting the url that accesses their API similar to the ‘http://tinyurl.com/api-create.php?url=’ url that is provided by TinyURL. Then replace the ‘http://tinyurl.com/api-create.php?url=’ with the url of your preferred service. I haven’t tested it on any other provider but if you do let me know how it works out.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Live
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz
  • YahooMyWeb

About This Site

WDBuc.com is the web site and blog of William D Buchanan, a web developer and technical consultant in the Tampa, Florida area. More...