We showed you how you can create a short URL using TinyURL and use it in the retweet text. But tinyurl is not the best solution for numerous reasons. They are not as tiny as bit.ly, and they do not provide the awesome stats that bit.ly has to offer. In this article, we will show you how to automatically shorten your WordPress Posts URLs using Bit.ly API.

Advantages of this Method

Once you implement this technique, you will not have to worry about creating a bit.ly URL for your post. Once a page is loaded, the URL would be created dynamically. There will only be one URL per post, so it will never duplicate the short URLs.

Before you do anything, you will need to get a Bit.ly API. To do this, head over tobit.ly and signup for an account. Then simply visit this URL:http://bit.ly/a/your_api_key

Once you got the API, open your theme’s functions.php file and paste the following code:

01 <?php
02 /* Based on code from David Walsh – http://davidwalsh.name/bitly-php */
03 function make_bitly_url($url,$format = 'xml',$version ='2.0.1')
04 {
05 //Set up account info
06 $bitly_login = 'YOUR LOGIN HERE';
07 $bitly_api = 'YOUR API KEY HERE';
08 //create the URL
09 $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$bitly_login.'&apiKey='.$bitly_api.'&format='.$format;
10 //get the url
11 $response = file_get_contents($bitly);
12 //parse depending on desired format
13 if(strtolower($format) == 'json')
14 {
15 $json = @json_decode($response,true);
16 return $json
17 }
18 else //For XML
19 {
20 $xml = simplexml_load_string($response);
21 return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
22 }
23 }
24 ?>

**NOTE: You must enter your Login and API Key.

Then you would need to open your theme’s single.php file (assuming that is where you want to display the short URL) and paste the following code right under the start of your loop:

01 <?php
02 //Check for post's shortened URL. Used with twitter feedback.
03 if(get_post_meta($post->ID, "short_url", true) != ""){
04 //Short URL already exists, pull from post meta
05 $short_url = get_post_meta($post->ID, "short_url", true);
06 }else{
07 //No short URL has been made yet
08 $full_url = the_permalink();
09 $short_url = make_bitly_url($full_url);
10 //Save generated short url for future views
11 add_post_meta($post->ID, 'short_url', $short_url, true);
12 }
13 ?>

Then paste this code anywhere inside your loop to display the short URL:

1 <?php echo $short_url; ?>

Now you can implement this technique with Twitter Anywhere or any other way you want.

Content Source