September 23, 2015

September 23, 2015
In this article, we are going to discuss about How to create Bit.ly URL for WordPress posts automatically. 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:

//create bit.ly url
function bitly()
{
    //login information
    $url = get_permalink();  //generates wordpress' permalink
    $login = 'imjp';    //your bit.ly login
    $apikey = 'R_11882237eac772b5d6126e895a06c43f'; //bit.ly apikey
    $format = 'json';   //choose between json or xml
    $version = '2.0.1';
     
    //create the URL
    $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
     
    //get the url
    //could also use cURL here
    $response = file_get_contents($bitly);
     
    //parse depending on desired format
    if(strtolower($format) == 'json')
    {
        $json = @json_decode($response,true);
        echo $json['results'][$url]['shortUrl'];
    }
    else //xml
    {
        $xml = simplexml_load_string($response);
        echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
    }
}

The code above is pretty much self explanatory.

Don't forget to change the login and apikey strings to match yours.

I hope you guys found this article useful.

0 comments:

Post a Comment