How to Create a Bit.ly URL for WordPress Automatically

Automatically Create a Bit.ly URL for WordPress Posts

Bit.ly is currently the most popular URL shorting service out there and for a good reason too. With bit.ly you can track your shortened URLs and much more. In this article I’m going to show you how to use bit.ly’s api create bit.ly urls automatically for WordPress posts.

In order to make use of Bit.ly’s API, you’ll need to:

  1. Signup at Bit.ly
  2. Get your API Key

Now that you have a login and API key, open your WordPress theme’s functions.php (just create one if you don’t have one) and paste the following code at the top of the document:

01 //create bit.ly url
02 function bitly()
03 {
04 //login information
05 $url = get_permalink(); //generates wordpress' permalink
06 $login = 'imjp'; //your bit.ly login
07 $apikey = 'R_11882237eac772b5d6126e895a06c43f'; //bit.ly apikey
08 $format = 'json'; //choose between json or xml
09 $version = '2.0.1';
10
11 //create the URL
12 $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
13
14 //get the url
15 //could also use cURL here
16 $response = file_get_contents($bitly);
17
18 //parse depending on desired format
19 if(strtolower($format) == 'json')
20 {
21 $json = @json_decode($response,true);
22 echo $json['results'][$url]['shortUrl'];
23 }
24 else //xml
25 {
26 $xml = simplexml_load_string($response);
27 echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
28 }
29 }

The code above is pretty much self explanatory.
Don’t forget to change the login and apikey strings to match yours.

I’ve modified David Walsh’s “Create Bit.ly Short URLs Using PHP” in order to generate bit.ly urls automatically with WordPress. Now you can display your bit.ly url anywhere inside the loop or post .

The result of <?php bitly(); ?> in this post is http://bit.ly/4UbQ66.

I hope you guys found this article useful :D !

You Might Like This Posts
  • How to change blog title be SEF
  • Social Bookmarking For WordPress Blog
  • Easy to Upgrade Wordpress Engine
  • Learn about WordPress SEO
  • How To Integrate Wordpress with Drupal CMS
  • Leave a Reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word