Shorter Shortlinks – If You Have WWW In Your Domain
September 17th, 2010 by Stephen Cronin (Please wait) [Shortlink]Earlier today, I read a post by Stephanie Leary about the shortlink functionality introduced in WordPress 3.0. Afterwards, I felt I should share the code snippet that I use to make my shortlinks even shorter.
Note: This is only for domains that have www in them – for example, I use http://www.scratch99.com/ rather than http://scratch99.com/
The the_shortlink Function
Stephanie’s post is about the the_shortlink template function. I won’t go into detail about what it does, but basically it creates a shortlink for your post and displays it. This is useful for people wanting to share the link on service such as Twitter, which limits the number of characters you can use.
Many people use Bit.ly or use a solution such as YOURLS by Ozh Richard and Lester Chan to create their own shortener, but the_shortlink function can be an effective alternative.
An Example Shortlink
I use the following code in my single.php:
<?php echo '['; the_shortlink('Shortlink','Shortlink to be used when sharing this article'); echo']';?>
My post on WordPress caching plugins for shared hosting has a URL of:
http://www.scratch99.com/2010/08/wordpress-caching-plugins-for-shared-hosting/
The extra code creates a shortlink which has a value of:
http://www.scratch99.com/?p=287
These two URLs lead to the same place, but the second one is obviously much shorter.
The Problem
See the www. in that URL? That’s 4 characters that don’t need to be there. That’s right:
http://www.scratch99.com/?p=287
and
http://scratch99.com/?p=287
both lead to the same place. 4 characters may not seem like much, but every character counts on Twitter!
The Solution
Drop the following code in your functions.php file:
add_filter('get_shortlink','sjc_alter_shortlink');
function sjc_alter_shortlink($shortlink) {
$shortlink = str_replace('www.','',$shortlink);
return $shortlink;
}
This will filter the shortlink returned by the_shortlink function and run the sjc_alter_shortlink function on it. That’s a very simple function does a replace on the shortlink to remove the www. and return the shorter link.
It’s not rocket science, but I hope that snippet helps someone out there.
Tags: twitter, url shorteners, WordPress, WordPress 3.0


Note that the WP plugin for YOURLS totally use WP’s shortlink function, so that’s transparent.
Hi Ozh,
Thanks for pointing that out. I haven’t actually dug into YOURLS yet although I’ve been meaning to for the longest time.
Stephen,
Thanks for this info. It may not seem like “rocket science” to you, but to most of us, that’s exactly what it is. So, the info that you’ve provided will be a big help.
Thanks,
Jhoe