Making Short WordPress URLs with Bit.ly and PHP

Tweet This Much to my chagrin, the latest update of WordPress.com Stats (v. 1.63) broke the internal shortlink functionality in WordPress (ie. the wp.me links that accompany every new post). After I realized this was causing my post content not to display properly, I pulled the get_shortlink() function off of my site and thought about what I should do next. After a little Googling, I came upon David Walsh‘s excellent article on how to create short URLs using PHP and the bit.ly API. It basically told me everything I needed to know, but since the API had changed since he wrote his article, I modified the function to make it v3 compliant (it’s possible that the 2.01 API he was using still worked, but I didn’t actually check). You can find my new version of the function down below.


< ?php
/* make a URL small */
function make_bitly_url($url,$login,$appkey,$format = 'xml',$history = 1)
{
//create the URL
$bitly = 'http://api.bit.ly/v3/shorten?login='.$login.'&apiKey='.$appkey.'&uri='.urlencode($url).
'&format='.$format.'&history='.$history;

//get the url
//could also use cURL here
$response = file_get_contents($bitly);

//parse depending on desired format
if(strtolower($format) == 'json')
{
$json = @json_decode($response,true);
return $json['data']['url'];
}
elseif(strtolower($format) == 'xml') //xml
{
$xml = simplexml_load_string($response);
return $xml->data->url;
}
elseif(strtolower($format) == 'txt') //text
{
return $response;
}
}

/* general usage */
$short = make_bitly_url('http://YOUR LONG URL','YOUR LOGIN','YOUR API KEY','xml');
echo 'The short URL is: '.$short;

?>

Because I wanted to use these short links on my blog in place of a “sharethis.com” widget, I added the make_bitly_url() function to my functions.php file and the following code to my Index Template (index.php) and my Single Post Template (single.php):


< ?php $the_title = get_the_title(get_the_ID()); ?>
< ?php $the_permalink = get_permalink(get_the_ID()); ?>
< ?php $bitly_link = make_bitly_url($the_permalink,'YOUR LOGIN','YOUR API KEY','xml'); ?>
Post to Twitter

8 thoughts on “Making Short WordPress URLs with Bit.ly and PHP”

  1. As far as I can tell this script works like a dream. Thanks for sharing. I’m not using it with WP —- just on my site — but it’s working great so far.

    Fantastic work!

  2. What if the bit.ly system returns an error? or even returns nothing (due timeout or serverdown) ?
    How can I catch the error?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Pop culture specialist.