WordPress Beginner show nicely tutorial about How To Automatically Shorten your Permalink using Bit.ly services. Why we need to shorten our URL? Shorten URL is good to share on many social web, social news, social media and social network such as Twitter, Facebook, Digg and many more..
Before we began using this tutorial, you need create your own Bit.ly API Key on this page.. after finish paste this code on your functions.php
<?php /* Based on code from David Walsh – http://davidwalsh.name/bitly-php */ function make_bitly_url($url,$format = 'xml',$version = '2.0.1') { //Set up account info $bitly_login = 'YOUR LOGIN HERE'; $bitly_api = 'YOUR API KEY HERE'; //create the URL $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$bitly_login.'&apiKey='.$bitly_api.'&format='.$format; //get the url $response = file_get_contents($bitly); //parse depending on desired format if(strtolower($format) == 'json') { $json = @json_decode($response,true); return $json['results'][$url]['shortUrl']; } else //For XML { $xml = simplexml_load_string($response); return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash; } } ?>
You need to change your LOGIN and API key on the code above. After finish, open your single.php and paste this code under start on your WordPress Loop
<?php
//Check for post's shortened URL. Used with twitter feedback.
if(get_post_meta($post->ID, "short_url", true) != ""){
//Short URL already exists, pull from post meta
$short_url = get_post_meta($post->ID, "short_url", true);
}else{
//No short URL has been made yet
$full_url = the_permalink();
$short_url = make_bitly_url($full_url);
//Save generated short url for future views
add_post_meta($post->ID, 'short_url', $short_url, true);
}
?>
And the last thing to do, paste this code anywhere on your loop
<?php echo $short_url; ?>
I hope this tutorial work on you, if you have any question you can discuss it here or contact WordPress Beginner.




great, thanks! I’m already using bit.ly for tweets, but it’s good to know, how to automatically short urls in my wordpress blog.
Pingback: Automatically empty Trash | Unlock IMEI Cellphones
Can I use another short URL service (like tiny.cc) with your code? What changes do I have to make?
The Shorten URL is good to share on many social web, social news, social media and social network.