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
Elegant Themes
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 »

Comments

  1. pkiula says:

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

  2. WpInformerUA says:

    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.

  3. Greg Winiarski says:

    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.

  4. Josh says:

    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.

    • Robert says:

      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.

  5. Ash Blue says:

    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

    • Editorial Staff says:

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

    • Jonathan Blundell says:

      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.

  6. Anwar says:

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

    Thanks

  7. Md Sajjadul Farooque Robin says:

    Obviously a handy article.

    Thanks

  8. Muhammad Asad says:

    Nice to see this great tutorial on your site!

  9. Ted Thompson says:

    Great, very helpful! Thanks

  10. FAQPAL says:

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

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.