Aug
20
2010

Create bit.ly Short URLs for your Posts in WordPress

by   |  Posted in Tutorials  |  8 comments

I have been working with the http://bit.ly API and decided to change the short URLs on my site to include the short URLs provided by http://bit.ly. The API is pretty straightforward and I created a few WordPress functions to to get it all working.

Before we even start, you would need to registered with http://bit.ly and then check out this page http://bit.ly/a/your_api_key to get your API key and your login.

Now, let’s add a function to automatically create a http://bit.ly short URL when you publish a post. We will hook into the publish_post action and then use the http://bit.ly API to fetch a shortened URL. Place the following into your theme’s function.php file.

add_action('publish_post', 'create_bitly');
 
function create_bitly($postID) {
	global $wpdb;
	$login = 'YOUR LOGIN'; // change this to your login
	$apikey = 'YOUR API KEY'; // change this to your API key
 
	$longURL = get_permalink($postID); // here we get the permalink to your post
 
	// This is the API call to fetch the shortened URL
	$apiurl = 'http://api.bit.ly/v3/shorten?longUrl='.urlencode($longURL).'&login='.$login.'&apiKey='.$apikey;
 
	// We are using cURL
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_URL, $apiurl);
	$results = json_decode(curl_exec($curl));
	curl_close($curl);
 
	$shortURL =  $results->data->url; // the short URL
 
	update_post_meta($postID, 'bitlyURL', $shortURL); // adding the short URL to a custom field called bitlyURL
}

You can read more about the http://bit.ly API here: http://code.google.com/p/bitly-api/wiki/ApiDocumentation

In order to add your new short URL to your header, you first need to remove the default shortlink tag and then create a function that will place the proper code between your <head> tags.

remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 ); // removing the default shortlink
add_action( 'wp_head', 'bilty_shortlink_head'); // adding the new bit.ly shortlink
 
function bilty_shortlink_head() {
	global $post;
	$shortURL = get_post_meta($post->ID, 'bitlyURL', true);
	if(!empty($shortURL)) {
		echo '<link rel="shortlink" href="'.$shortURL.'" />'."\n";
	} else {
		echo '<link rel="shortlink" href="'.get_bloginfo('url').'?p='.$post->ID.'" />'."\n";
	}
}

If you want to display your new short URLs, you can do so by using the `wp_get_shortlink()` function. But first you need to make sure that WordPress knows to replace the default short URL with the new http://bit.ly short URL.

add_filter('pre_get_shortlink', 'get_bitly_shortlink'); // filtering the WP function
 
function get_bitly_shortlink() {
	global $post;
	$shortURL = get_post_meta($post->ID, 'bitlyURL', true);
	if(!empty($shortURL)) {
		 return $shortURL;
	} else {
		return get_bloginfo('url').'?p='.$post->ID;
	}
}

You can place the following code anywhere within the loop of your single.php theme file to display your short URL.

Short URL: <a href="<?php echo wp_get_shortlink($post->ID); ?>" title="<?php the_title(); ?>"><?php echo wp_get_shortlink($post->ID); ?></a>

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , , , ,

Short URL: http://bit.ly/9FE1Fw

Discussion 8 Comments

  1. Gökhan on August 25, 2010 at 4:50 am

    Thanks very much.
    This tip very useful.

  2. Christopher Ross on August 25, 2010 at 11:07 am

    Chris, this is a great tutorial.

    The Bit.ly engine is a great URL shortener, have you thought about writing it as a plugin?

    • c.bavota on August 25, 2010 at 11:22 am

      Working on a plugin right now with Media Sidekick. Should be ready shortly.

  3. Nayan on November 26, 2010 at 3:02 am

    Thanks…. After lots of search i found it here. Thanks again Cheers :)

  4. zeaks on January 9, 2011 at 2:44 am

    Thanks for the tutorial, just what I was looking for. I’ve had problems with plugins for this.

  5. zeaks on January 10, 2011 at 3:28 am

    Any idea why I can’t get to work for pages too? I’m using Twenty Ten theme, and have added it to single.php, page.php and one-column.php but it will only show the default shortlink, not the bit.ly one. I can’t figure it out

  6. Jelbee on February 15, 2011 at 7:03 pm

    Im not using wordpress, is it possible to use this code on other php site?

  7. Joan on April 13, 2011 at 10:56 pm

    Another easier option with less functionality:

    function bitly($longurl){
    $bitly_username = 'USERNAME';
    $bitly_apikey = 'APIKEY';
     
    $url = "http://api.bit.ly/shorten?version=2.0.1&amp;longUrl=$longurl&amp;login=$bitly_username&amp;apiKey=$bitly_apikey&amp;format=json&amp;history=1";
    $s = curl_init();
    curl_setopt($s,CURLOPT_URL, $url);
    curl_setopt($s,CURLOPT_HEADER,false);
    curl_setopt($s,CURLOPT_RETURNTRANSFER,1);
    $result = curl_exec($s);
    curl_close( $s );
     
    $obj = json_decode($result, true);
    return $obj["results"]["$longurl"]["shortUrl"];
    }