Beginner's Guide for WordPress - Start your WordPress Blog in minutes.
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

How to Automatically Shorten Your WordPress URLs with Bit.ly

Last updated on by
Follow WPBeginner on YouTube
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


Editorial Staff at WPBeginner is a team of WordPress lovers led by Syed Balkhi. Page maintained by Syed Balkhi.

WPBeginner's Video Icon
Our HD-Quality tutorial videos for WordPress Beginners will teach you how to use WordPress to create and manage your own website in about an hour. Get started now »
  • pkiula

    Hi. Very useful article! Do you have a similar plugin or code for SnipURL? Thanks!!!

    • http://www.wpbeginner.com/ wpbeginner

      @pkiula Haven’t seen it.

  • WpInformerUA

    It will create short links only for new posts?

    Don’t work on my site( Use current version of WordPress. It don’t create a short link. Only ‘bit.ly’ link.

  • http://ditio.net Greg Winiarski

    It’s short and sweet however, if allow_url_fopen is disabled (which isn’t common but happens from time to time), this won’t work, user will be shown only PHP warning.

    In my opinion better approach is to use cURL library or even better Snoopy library that is bundled wi
    th the WordPress.

  • Josh

    Can’t seem to get this to work. Have tried on 2.9.5 and 3.0 RC2. Tried moving the call all around the loop but all this ever outputs for me is:
    http://bit.ly

    I have checked, and re-checked everything from login and api to going over each line of code.

    • http://following2leading.com Robert

      I had a similar problem with an older version of WordPress, and I resolved it by changing “$full_url = the_permalink();” to “$full_url = get_permalink();”. I also had to remove the “if…else” part of the code and only use the code inside the else condition, but that may have been a caching issue. Hope this helps.

      • http://appcrunch.co.uk Josh

        Hi Robert,

        Thanks for the response your suggestion worked perfectly. I had to do both changes. I added the following to my loop:

        Code is here: http://wordpress.pastebin.com/ha7JcNdR

        • http://www.jdblundell.com Jonathan Blundell

          i had to make that change as well for it to work on my site.

      • http://www.geekhq.com.br Anderson Batata

        Hey man thanks! had the same problem. I did both things and it worked. Thanks

  • http://www.ashbluewebdesign.com Ash Blue

    Although not as effective, WordPress 3.0 has much simpler built in short url capabilities with the short_link template tag. More info here http://codex.wordpress.org/Template_Tags/the_shortlink

    • http://www.wpbeginner.com Editorial Staff

      In WordPress 3.0 you can use wp.me URLs with simple API. That would make life even more easier.

    • http://www.jdblundell.com Jonathan Blundell

      I’m having difficulty getting the shortlink to work by actually displaying the shortlink.

      When I use echo the_shortlink; it simply adds a link that says (as the codex suggests) The is the short link.

      This tutorial is great – except that bit.ly’s service has gone down today and thus all my individual posts are taking forever to load because of it. I’ve had to strike the code from my sites to get around it for the time being.

      Would love to simply use the “native” WordPress shortener either with wp.me or my own domain if I could find a way to do it.

  • http://webdevstar.com Anwar

    This is great. Now I can shorten urls for retweets or maybe other urls on my site.

    Thanks

  • http://coderfrombd.com Md Sajjadul Farooque Robin

    Obviously a handy article.

    Thanks

  • http://bilaunwan.co.cc Muhammad Asad

    Nice to see this great tutorial on your site!

  • http://www.goblinridge.co.uk Ted Thompson

    Great, very helpful! Thanks

  • http://www.faqpal.com FAQPAL

    Excellent tutorial, and a fantastic idea. Thanks for the share.