UPDATE: There is now a plugin which will automatically create the bit.ly links for you.
Have you ever wondered how to automatically create bit.ly links in WordPress like this:
Well it’s dead simple. First you need a bit.ly account and an API key then add the following code to your theme’s functions.php file:
function bitly() { $url = get_permalink(); $analytics = $url . '?utm_source=bitly&utm_medium=link&utm_campaign=urlshortener'; //your Analytics code $login = ''; //bit.ly username $apikey = ''; //bit.ly api $format = 'json'; $version = '2.0.1'; $bitly = 'http://api.bit.ly/shorten?version=' . $version . '&longUrl=' . urlencode($analytics) .'&login=' . $login . '&apiKey=' . $apikey . '&format=' . $format; $response = file_get_contents($bitly); if (strtolower($format) == 'json') { $json = @json_decode($response, true); echo $json['results'][$analytics]['shortUrl']; } else { $xml = simplexml_load_string($response); echo 'http://bit.ly' . $xml->results->nodeKeyVal->hash; } }
It’s that simple. Then all you need to do is add the line:
<?php bitly(); ?>
to your template where you want the link to appear and you are good to go.
The bit.ly link is automatically created via the API call and then the Analytics tracking code is adding to the URL. This Analytics code is preserved through the bit.ly link and that link can be tracked through your Analytics Account.
Thank you devmoose.com for the original code.