WordPress: Auto URL Shortening
Everyday there are scores of new links shared, re-tweeted, posted, and emailed by people like you and I. Because of social media platforms like Twitter and Facebook, our love for sharing information, tutorials, freebies, etc., has never been stronger!
The Proposition
As a WordPress developer/designer, how would you like if URLs on your WordPress site were automatically shortened as soon as you publish? This would mean instantly available shortened URLs for sharing/posting AND statistics of your links!
Here’s How
We are going to build the Auto URL Shortening feature within your WordPress theme using the bit.ly API. Let’s start with the functions.php file found within your theme.
The functions.php file is included in most WordPress themes as a place to drop custom functions to be used from the theme. If this file doesn’t exist in the theme you are using, go ahead and create it.
Add 3 functions within the functions.php file
function makeshorturl()
{
}
function shorturl_metabox()
{
}
function showshorturlbox()
{
}
The first function, makeshorturl(), as the name suggests will be creating a short URL for us. The second and the third functions will work together to show us the short URL in the admin editor.
Shortening the link
function makeshorturl()
{
global $post;
$short_url = json_decode(file_get_contents('http://api.bit.ly/v3/shorten?login=[username]&apiKey=[apikey]&longURL='.urlencode(get_permalink($post->ID)).'&format=json'));
if($short_url->status_code=="200")
{
$short_url = $short_url->data->url;
}
else
{
$short_url = "Bit.ly Error! ".$short_url->status_txt;
}
do_action('makeshorturl');
return $short_url;
}
The first line in this function declares WordPress’s global $post variable which holds all the data for the current post. We extract the permalink of the current post using the get_permalink() function and supplying the current post’s id. We then take the permalink and pass it on to bit.ly’s API which returns us a short URL within a JSON object. Next we extract the short URL. If an error occurs we simply return the error.
The do_action() method in WordPress makes this function hookable with other functions/hooks and the function can be used within theme using the hook – makeshorturl().
Want to know more about do_action() and wordpress hooks?
Lets look at the api call in more detail
http://api.bit.ly/v3/shorten?login=[username]&apiKey=[apikey]&longURL='.urlencode(get_permalink($post->ID)).'&format=json
It’s really quite simple.
The login parameter would expect your login over at bit.ly (don’t have one? create one here). The apiKey parameter accepts the API key given to each bit.ly account. If you already have an account you can find the API key here. The longURL parameter expects an encoded long URL string that needs to be shortened, and this is where our custom permalinks get passed. The format parameter expects one of the three values – json, xml or text; depending on the format value specified, the API returns the shortened url (and more data) as JSON, XML or text respectively. By default, if format is not specified, it returns a JSON object. For more info on the bit.ly API, refer the API documentation. Once the bit.ly API sends the JSON object back, we use PHP’s json_decode function to decode the JSON object into a PHP5 object.
Adding the shortened URL to the admin editor
Once the permalink has been shortened, we need to make it available in the backend. To do this, we use the two functions as outlined below.
function shorturl_metabox()
{
if(is_admin())
{
add_meta_box('bitlyurl',__('Short URL','short-url'),'showshorturlbox','post','side');
add_meta_box('bitlyurl',__('Short URL','short-url'),'showshorturlbox','page','side');
}
}
The shorturl_metabox will first check if the user is within the admin section of the wordpress based site/blog. Then we add a meta box to the admin page.
A Meta box in WordPress basically is a box which sets and gets meta information about a post. Default meta boxes include Post Tags, Discussions and so forth.
The add_meta_box function takes five parameters:
- the HTML id of the box
- the label/title of the box
- the callback function which would render the box contents
- the type of write screen – post or a page
- the position or context where the box would be located – Normal, Advanced or Side.
As you can see, that when the function “adds” the meta box to the admin view, it calls the showshorturlbox function which renders the contents of the meta box, as shown below.
function showshorturlbox()
{
echo '<label for="bitlyurl">'.__('Shortened URL','short-url-label').': '.makeshorturl().'</label><br/><br/>';
}
The function echoes the short URL in a label, thus making it available to be shared by the authors of the post/page. We are calling makeshorturl() which fetches or generates the shortened URL via the bitly API.
Bringing it together
Finally we use the following three lines which attach our makeshorturl() function to the publish_post and publish_page hooks and attaches shorturl_metabox to the do_meta_boxes hook that generates the meta boxes.
add_action('publish_post','makeshorturl');
add_action('publish_page','makeshorturl');
add_action('do_meta_boxes','shorturl_metabox');
Complete Code within functions.php
function makeshorturl()
{
global $post;
$short_url = json_decode(file_get_contents('http://api.bit.ly/v3/shorten?login=[username]&apiKey=[apikey]&longURL='.urlencode(get_permalink($post->ID)).'&format=json'));
if($short_url->status_code=="200")
{
$short_url = $short_url->data->url;
}
else
{
$short_url = "Bit.ly Error! ".$short_url->status_txt;
}
do_action('makeshorturl');
return $short_url;
}
function shorturl_metabox()
{
if(is_admin())
{
add_meta_box('bitlyurl',__('Short URL','short-url'),'showshorturlbox','post','side');
add_meta_box('bitlyurl',__('Short URL','short-url'),'showshorturlbox','page','side');
}
}
function showshorturlbox()
{
echo '<label for="bitlyurl">'.__('Shortened URL','short-url-label').': '.makeshorturl().'</label><br/><br/>';
}
add_action('publish_post','makeshorturl');
add_action('publish_page','makeshorturl');
add_action('do_meta_boxes','shorturl_metabox');
Usage
If you did like to show off the shortened URL to your users simply insert this code where you want the short URL to show up:
<?php echo makeshorturl(); ?>
BONUS
Want a ready-to-use solution? Here’s the plugin version of the above code that will generate the shortened URLs on the fly for you to share. If you did like to call the functions from within the theme template, you can do so by using:
<?php echo wps_hook(); ?>
Note: Above tag is for the plugin only.
PS: The plugin can also show number of clicks on a shortened link :) per shortened URL



This is a great tutorial to show how to connect everything together and make bit.ly work, you can also head over to http://theeasyapi.com and see other URL Shortener services that are available. You can use is.gd, to.ly, bit.ly, 1click.at, and many others.
The nice thing about using a different URL Shortener besides bit.ly is that you don’t have to worry about “unspecified error” messages, and using a wrapper service like The Easy API provides stability.
Thanks for the the tutorial. There were others posted but yours is the only one that worked on my blog.
Question: Is there a way to make a link?
I’m using the code and not the plugin and rather not use the plugin. Thanks!
I’m not 100% sure what you mean by “make a link”, but if you mean to include the bit.ly link on each post’s page in your WordPress theme, yes.
Simply use the makeshorurl(); function anywhere on the page in your theme.
I’m sorry, I mean, make it an active like. For example see right above the comments: http://socialwayne.com/2010/06/01/triout-check-in-golden-carral-cary/
The makeshorurl(); displays the bit.ly url but it’s not an active link to click. I tried a href = “makeshorurl();” “makeshorurl();” but that didn’t work.
Thanks
@Wayne : Hey wayne, if you did like to make it an active link, use this …
<a href="<?php echo makeshorturl(); ?>">Keyworks/Anchor Text </a>
Note the tags, the echo and the missing “t” in the makeshorturl(); Hope this helps!
Thanks, I swear I tried that but oh well, it’s working now: See: http://socialwayne.com/2010/06/01/triout-check-in-golden-carral-cary/
at the bottom. It shows the bit.ly url as an active link now.
Rock on!
Thanks for the help
Glad it’s working :) \m/
very nicely explained! thumbs up!!!!!
*confused* Does this tutorial help me rewire all the link in a post to bit.ly? Thats what I’m looking for.
If I write a blog post about rowing and I include 7 links to different rowing sites then I want all those links to go through bit.ly first.
Is this what we’re talking about?
Hey Mike,
No, this only create’s a bit.ly link out of the permalink URL and makes it available for sharing. I do have a plugin ready to go – this does convert all links within a post to bit.ly URLs, would you like to test it for me? and give me some feedback, before I release it?
please yes I would like to test it!
If you still want me to test it you can email the plugin to me at mikeontv2007@gmail.com
Thank’s for this plugin. how do iput my short url at end of post ?
Thanks for the post.
All I wanted to know was how to implement the wordpress do_action. There aren’t many examples except wordpress’ files like the post-template.php.
@Gemma,
do_action creates a hook. Its a function that takes two types parameters, the first one being the name of the hook(which by standard is the same as the function for which you are creating the hook, but can be different too) and the second being the parameters that the hook passes on to the function.
Its really simple, it lets you create a hook (Action/Filter depending on the function you are creating this hook for). Hope this helps. If you are still confused, mail me and we can go over hooks.
PS: http://codex.wordpress.org/Function_Reference/do_action have a read here too..
Brilliant tutorial. But WordPress has now implemented this by default. Then also if someone wants to use the bit.ly can use this tutorial.
Great tutorial. This is the easiest and nicest method I’ve seen to integrate bit.ly with WordPress. I have one question, does the bit.ly api call occur every time a post is loaded or only when it’s published?
it will generate the shortlink when a page/post is published! hope this helps!
Thanks designerfoo,
This is the only tutorial that worked for me!
One question – you said in the above comment that the API call is done only when a post is published. So where is the short URL stored in the database?
Currently in the above code, it does not save to the database but requests the URL directly from bit.ly. If using in production, I would advice using a custom table that holds these values so that its faster while retrieving the shorter urls. Alternatively you can cache these in plain txt files or yet again use a NoSQL db with WP.. just thinking aloud here…but you get the picture, right?
Txt file won’t do. So, I made a little change in your code to save short URL to the database along with a post.
Thanks, once again.
Hello there, i’m wondering if this plugin works in wordpress 3.4.1 because i dont see it in wordpress.org/plugins.
Do you explain why?
Cheers men, keep your good work alive