Code snippet #2 - Shorten Links Using

Following the first snippet, here is another small one to shorten a link using I chose over other link shortening services due to a simple reason: Twitter uses it as default (by now).

Code snippet #2 - Shorten Links Using


Create a shortened URL using This is extremely useful for your visitors, as they don’t have to look any further - just grab it to use right away.


  • A account (and API key). You can create one for free at their site in seconds. Once logged in, head to Account section and look for a long ugly string starting with “R_”.
  • PHP 5 >= 5.2.0. Your host doesn’t support PHP 5? Claim your money back and find another host.

The Code

function get_shortened_url($url)
    $bitly_api_key = 'YOUR KEY HERE';
    $bitly_username = 'YOUR BIT.LY USERNAME HERE';
    $data = file_get_contents("$url&login=$bitly_username&apiKey=$bitly_api_key");
    $data = json_decode(utf8_encode($data));
    if ($data->errorCode)
        return false;
    return $data->results->$url->shortUrl;
// now use it
echo get_shortened_url('');
// how about WordPress?
// Just place the function above somewhere in your functions.php theme page and then
// 1. inside The Loop
echo get_shortened_url(get_permalink());
// 2. outside The Loop
echo get_shortened_url(get_permalink($post->ID));

  • Nice thanks, works well :)

You can follow any responses to this entry through the RSS 2.0 feed.