(+84) 463.28.7979

How to Automatically Shorten Your WordPress URLs with Bit.ly


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 to bit.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:

<?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;
}
}
?>

**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:

<?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);
}
?>

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

<?php echo $short_url; ?>

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

Source: Zach from Build Internet

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>