How To Automatically Generate Short URLs for Your Posts

Using short url tools have become common place across the web in recent years, part of this is the usage of Twitter and being restricted to 140 characters. Long urls took up entire tweets forcing tweeters to use these tools.

Twitter now have their own shortening tool t.co, but you can still use your own short links on Twitter.

What I’m going to show you today is a simple tutorial of how to generate your own short urls for your posts, and then display the short url on each of your posts.

I have used two short url services as examples, one with an API key and one without.

TinyUrl

Open functions.php and add:

function getTinyUrl($url) {
$tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
return $tinyurl;
}

Open single.php and add where you would like the link to display:

<?php
$tinyurl = getTinyUrl(get_permalink($post->ID));
echo 'here is a tiny url link: <a href="'.$tinyurl.'">'.$tinyurl.'</a>'
?>

bit.ly

If you don’t want to use TinyUrl and would opt to use a service such as bit.ly here is how you would do it to create a bit.ly link.

OK, first thing first, you will have to register with bit.ly to get your login name and API which is required, and must be added in the following snippet.

Open functions.php and add:

function getBitly($url) {
$bitly = file_get_contents("http://api.bit.ly/v3/shorten?login=BIT.LY LOGIN NAME&apiKey=BIT.LY API KEY&longUrl=$url%2F&format=txt");
return $bitly;
}

(note: the bit.ly API key usually looks something like R_43756h65657657d767)

Open single.php and add where you would like the link to display:

<?php
$bitly = getBitly(get_permalink($post->ID));
echo 'here is a bitly link: <a href="'.$bitly.'">'.$bitly.'</a>'
?>

Conclusion

This will work with most short url services, and you will have to edit the code slightly if you opt to use any alternatives, some require an API to shorten the link so remember to add that when you change the code.

You Might Also Like