Build Your Own URL Shortening and Redirection Service in WordPress

deliciousdiggstumblefloatdzonePrint Articlecomments rss

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

Have you seen those cryptic short URLs popping up everywhere - on web pages and even in Twitter or Plurk? If you build websites, you might wonder, “Why bother?,” especially since all the link juice ends up going to the service instead of to the source URL. This article discusses their uses, lists some services, and explains how you can create your own custom version in WordPress. It also covers a few concepts in the tutorial sections:

  1. One way to use WordPress Custom Fields.
  2. How to create conditional JavaScript code, based on PHP variables.
  3. How to redirect a web page in WordPress.

Short URL Uses

To date, short URLs have a very small number of uses:

  1. A replacement for when space is at a premium, such as on Twitter, Plurk, or similar services.
  2. Use in podcasts/ vodcasts/ screencasts, to make it easier for listeners/ viewers to find an article.
  3. Mask affiliate URLs.
  4. Also making appearances in print.
  5. Use for an online treasure hunt?

Know of any other uses? Short URLs have very specialized uses, but they’re good for that - especially #1. For use #2, the short URLs need to be friendlier than the standard cryptic URL - something discussed in detail below.

Services

Despite their focused use, there are numerous URL shortening services/ solutions, and they fall into a few categories:

  1. Privately hosted, random cryptic URLs.
  2. Self-hosted code, random cryptic URLs.
  3. Privately hosted, refined URLs.
  4. Self-hosted, refined URLs.

The screenshot below is an example of category #3 - a live demo of Khoi Vinh’s Shorty, which you can host a copy of, and which gives you control over the “short” URLs.

There are far too many URL shortening services to list them all here. Mashable had a list of 90+ URL shortening services earlier this year. Here are a few more services not on the Mashable list:

  1. BrokenScript. (Allows a “seed” string as clue.)
  2. elfURL.
  3. Lesslink.
  4. QuickURL/Qurl. (Offers picture hosting.)
  5. RURL.
  6. Shurl.org.
  7. Shrinkster.com.
  8. Snipr, whose API is used by Snipurl.
  9. Snurl.
  10. TinyURL.com.au.
  11. Twurl (now incorporated into Tweetburner).
  12. URL(x).
  13. URL123.
  14. Urlborg.
  15. URLGap. (Allows for a tag to be used.)
  16. ZipMyURL.
  17. zURL.ws.

Several of the above services allow some degree of finer control over the final short URL. A few offer APIs or downloadable, self-hosting source code.

The Drawbacks of Using an External Service

Most existing URL shortening services are used when space is at a premium, so the fact that the URLs are cryptic doesn’t usually matter. But there are some downsides with using an outside service, whether for casual use or for a production website:

  1. Link juice goes to someone else’s domain.
  2. What happens if they go offline or even out of business? The short links you’ve used will break, and users will not find the target URL. (At the time of this writing, at least five services were unavailable, and at least three not listed here are no longer in service.)
  3. What if you want to use short URLs in print, or more to the point, in web video/ screencasts? Cryptic URLs are not easy to remember when flashed for a few seconds. They’re even harder if you’re listening to them on an audio-only podcast. Friendlier URLs are necessary, though some services do offer this option.
  4. What if you want to associate extra content with a short URL, and have the content be searchable somewhere? (Explained in more detail below.)

Create Your Own “Tiny URL” Site in WordPress

If you have very specialized needs for a short-URL service, consider running your own, for your use only. For example, I’ve been doing a lot of podcasting/ screencasting, and I’m always reluctant to mention/ show the URL of an article I want to reference. Most people are not going to remember something really long nor something cryptic. If I have a substitute that’s short and easy to remember, this could be a boon for listeners.

In a related use, my podcasts/ screencasts often have accompanying accompanying articles that will list the necessary URLs. However, I can’t record the podcast with the location of the URL because it doesn’t exist yet. Catch-22. And if the podcast is living at an audio/video sharing site, or is embedded at someone else’s site, listeners might have difficulties finding the corresponding article.

To summarize the functional requirements:

  1. I need complete control of the redirect URL, not random alphanumeric characters.
  2. I’d like to attach some text and possibly images to the short URL page so that users can browse the site and find what they want. If I don’t have massive quantities of redirect posts in my service, they will not even have to remember the short URL.
  3. Alternately, users can also search for a site name or keyword at my service, to help pinpoint the redirection they’re looking for. Again, they don’t have to remember the short URL.

So to satisfy all these needs, I need my own short URL service. Obviously, if the URLs are going to be friendly and easy to remember, they’re not necessarily going to be as short as the typical cryptic short URL. If that’s not a concern, then the rest of this post covers how to set up your own URL shortening and redirection service in WordPress. My live example, Qurly.net, uses WP 2.5.1, but everything should work in early versions of WP.

[Note that the code below gives you complete control over the "short" URL. If you want something more random and don't mind the cryptic URLs, check out Wnyia.org's Making Your Own Tiny URLs with PHP.]

Process

The short URL redirection process I use requires WordPress Custom Fields. Here is a summary of the general process, which is expand on below:

  1. Create a new post and assign a category of “Redirect”. (This is actually optional, though if you use your own service for both regular blog posts and URL redirection, you might want to make redirect “posts” distinct and filter them out on the home page. I don’t do that because I actually want them to appear on the home page.)
  2. In the post, set up a Custom Field for the redirect URL: redirect-url. For the value of redirect-url, give it the URL that the short URL will redirect to.
  3. Change the post’s slug to whatever short URL you want  (done in post Edit mode). Don’t use forward slash, “/”, backslash, “”,  spaces or any other unacceptable URL slug characters. (Forward slashes are reserved for use in full URLs, not in the slugs.) Instead, consider using either underscore, “_”, or hyphen, “-”.
  4. Save the post.
  5. Test it by either clicking the post’s permalink from the homepage, or by typing in the short URL directly in your browser.

Of course, you need handler code to do the actually redirect. This is discussed shortly.

The snapshot below is how the Custom Fields pane looks in WP 2.5.1 when you are editing a post (new or existing).

I’ve used the Field name redirect-url, as that’ll be tested for in the handler code. Once you create a custom field name the first time, it’ll be available in the left-side dropdown menu for all other posts (new or existing).

Next, you have to edit the WordPress post slug. The snapshot below shows you where to find it in WP 2.5.1 (which is different than past versions):

Now, just save the post and test it.

The Handler Code

I’ll warn you before hand that the handler code looks very convoluted (though I’ve seen worse when developing interactive sites in Perl, JavaScript and HTML). If you look closely, though, it’s not really too complicated. It’s one of those situations where the explanation is lengthier than the code.

Here is a code fragment from a modified single.php template file (using WordPress’ Default theme):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php get_header(); ?>
 
	<div id="content" class="widecolumn">
	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
 
 
	<!-- Short URL Redirection Code -->
	<?php
	if ( $redirecturl = get_post_meta($post->ID, 'redirect-url', true) )
	{ ?>
		<?php
		echo "Redirect URL: [". $redirecturl. "]<br/>";
		?>
		<script type="text/javascript">
			location.href ="<?php echo $redirecturl; ?>";
		</script>
 
	<?php } ?>

There is more than one way to do a page redirect, but you cannot use PHP’s header() function because WordPress’ header.php file will have already sent out HTML header information. I also don’t want to have to make any changes to the web server’s .htaccess file, since not everyone has access. So here is the basic handler logic in use, which lives in your WP theme’s single.php file.

  1. Inside the WP “loop” code, before rendering the post page, check if the current page has Post Meta information (Custom Fields). Specifically, we’re testing for a Custom Field called “redirect-url”, using the WP function get_post_meta() inside a block of PHP code. The variable $post->ID supplies the ID of the current post. The third parameter, true, says to only grab a single value of redirect-url. (WP allows you to use the same custom field name multiple times in the same post. If we use “false”, then the value returned by get_post_meta() is an array, even if there’s only one value. Since we only use redirect-url once per “post”, it’s simpler to grab a single-valued variable than an array.
  2. Once we have the value of redirect-url, we assign it to the variable $redirecturl. (If there is no redirect-url Custom Field, the code falls through the PHP if statement and the page will get rendered.
  3. The PHP echo statement displays the redirect URL on screen. This is purely for debugging purposes. Feel free to remove it.
  4. Inside the PHP if statement, we do a redirect by using a JavaScript location.href assignment. Here’s where the code is a bit convoluted. The redirect URL is stored in a PHP variable, but we’re using JavaScript code for the redirect. So we need to use a fragment of PHP code inside the JavaScript code. Once a new URL has been assigned to location.href, the redirect is automatic.

Note: If you have a theme that combines index.php and single.php into index.php, you’ll have to find where the template code renders a single post page’s contents and insert the handler code accordingly.

How a Reader Uses Your URL Shortening Service

This is set up at my Qurly.net site, on WP 2.5.1. I have only two examples set up, at the time of this writing, though they should be sufficient to demonstrate the redirection at work.

When you’ve set up a redirect “post” and provided the short URL either in a web page or maybe in a podcast, a curious user can use this redirect service in a few ways:

  1. Browse the home page, find the desired “post”, then click on the permalink. (See snapshot above.)
  2. Use the site’s Search for a keyword or target site name. Click on a search result’s permalink. (At the time of writing, using Search at Qurly.net results in headlines only, no descriptions.)
  3. Type in the short URL directly into the browser.

All of these ways will cause a redirect to the target URL, if the redirect post is set up correctly.

So if I have a podcast and mention some “CSS Grids retrospective” article at “Webdevlounge.com”, I might mention a custom short URL of “qurly.net/webdev-cssgrids”. That’s still a bit harder to remember, but the listener can also search for either “CSS Grid” or “Webdevlounge” at Qurly.net. (For screencasts/ vodcasts, I can display the short URL I’ve set up.)

This is arguably a much simpler experience for podcast listeners, as opposed to needing to remember some big long URL or a short cryptic one that’s not memorable at all.

The full code of the single.php I’m using (based on WP 2.5.1’s Default Theme) can be downloaded here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php get_header(); ?>
 
	<div id="content" class="widecolumn">
 
	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
 
 
	<!-- Short URL Redirection Code -->
	<?php
	if ( $redirecturl = get_post_meta($post->ID, 'redirect-url', true) )
	{ ?>
		<?php
		echo "Redirect URL: [". $redirecturl. "]<br/>";
		?>
		<script type="text/javascript">
			location.href ="<?php echo $redirecturl; ?>";
		</script>
 
	<?php } ?>
 
 
		<div class="navigation">
			<div class="alignleft"><?php previous_post_link('&laquo; %link') ?></div>
			<div class="alignright"><?php next_post_link('%link &raquo;') ?></div>
		</div>
 
		<div class="post" id="post-<?php the_ID(); ?>">
			<h2><?php the_title(); ?></h2>
 
			<div class="entry">
				<?php the_content('<p class="serif">Read the rest of this entry &raquo;</p>'); ?>
 
				<?php wp_link_pages(array('before' => '<p><strong>Pages:</strong> ', 'after' => '</p>', 'next_or_number' => 'number')); ?>
				<?php the_tags( '<p>Tags: ', ', ', '</p>'); ?>
 
				<p class="postmetadata alt">
					<small>
						This entry was posted
						<?php /* This is commented, because it requires a little adjusting sometimes.
							You'll need to download this plugin, and follow the instructions:
							http://binarybonsai.com/archives/2004/08/17/time-since-plugin/ */
							/* $entry_datetime = abs(strtotime($post->post_date) - (60*120)); echo time_since($entry_datetime); echo ' ago'; */ ?>
						on <?php the_time('l, F jS, Y') ?> at <?php the_time() ?>
						and is filed under <?php the_category(', ') ?>.
						You can follow any responses to this entry through the <?php post_comments_feed_link('RSS 2.0'); ?> feed.
 
						<?php if (('open' == $post-> comment_status) && ('open' == $post->ping_status)) {
							// Both Comments and Pings are open ?>
							You can <a href="#respond">leave a response</a>, or <a href="<?php trackback_url(); ?>" rel="trackback">trackback</a> from your own site.
 
						<?php } elseif (!('open' == $post-> comment_status) && ('open' == $post->ping_status)) {
							// Only Pings are Open ?>
							Responses are currently closed, but you can <a href="<?php trackback_url(); ?> " rel="trackback">trackback</a> from your own site.
 
						<?php } elseif (('open' == $post-> comment_status) && !('open' == $post->ping_status)) {
							// Comments are open, Pings are not ?>
							You can skip to the end and leave a response. Pinging is currently not allowed.
 
						<?php } elseif (!('open' == $post-> comment_status) && !('open' == $post->ping_status)) {
							// Neither Comments, nor Pings are open ?>
							Both comments and pings are currently closed.
 
						<?php } edit_post_link('Edit this entry.','',''); ?>
 
					</small>
				</p>
 
			</div>
		</div>
 
	<?php comments_template(); ?>
 
	<?php endwhile; else: ?>
 
		<p>Sorry, no posts matched your criteria.</p>
 
<?php endif; ?>
 
	</div>
 
<?php get_footer(); ?>

Other Uses

I’m using Qurly.net for a very specialized use: in podcasts and vodcasts, so that people have an easy way to quickly find a specific post. I could also use it in some of the other ways mentioned earlier, though I do little affiliate blogging. Still, the way this is set up leaves room for future possibilities.

Final Thoughts

Qurly.net is set up for my use, though I’m offering very limited access to only the first 10 people that explicitly request it in the comments of this article. (If you use it for spam, pr0n, unethical or illegal purposes, you’ll be blacklisted.) Also, if you’re already a colleague of mine, it’s open to you as well. As for others, my apologies but I just don’t have time at present to enable and monitor multiple accounts.

 
raj

A post by raj

Visit personal site

Subscribe to comments

RSS

 
 

12 Comments

  1. [...] Build Your Own URL Shortening and Redirection Service in WordPress | WebDevLounge | design, developm… - [...]

    By Delicious Bookmarks for your consumption. | styl.eti.me, August 27th, 2008 at 6:16 pm

  2. [...] Raj Dash of WebDevLounge.net discusses URL shortening services, their uses, and explains how you can create your own custom version in WordPress. He also covers one way to use Custom Fields, how to create conditional JavaScript code, based on PHP variables, and how to redirect a web page in WordPress. [Link] [...]

    By Build Your Own URL Shortening and Redirection Service — WPCandy — WordPress Themes, Plugins, Tips, and Tricks, August 29th, 2008 at 8:10 am

  3. Great write up. I’ve submitted it to WPVote.

    One question is what happens to the link juice?

    The PHP echo statement displays the redirect URL on screen. This is purely for debugging purposes. Feel free to remove it.

    It might be a good idea to leave it there, but to turn it into a link. Because we’re redirecting using JavaScript, I don’t think Googlebot’s going to see that, or pass any link juice on. If you have a link on the page, it will pass some PR to the link (ie the end page). Of course you’ll be sharing it with any other links on the page, if you have sidebars etc.

    The ideal solution would be to return a 301 header, so that all the link juice would be passed on directly to the end page, but as you’ve pointed out, we can’t use PHP to set headers, so maybe adding the link to the page is the best bet.

    By Stephen Cronin, August 29th, 2008 at 2:08 pm

  4. as an aside, http://is.gd does 301 redirects and will pass link juice correctly.

    By mjc, August 29th, 2008 at 8:56 pm

  5. [...] - Build Your Own URL Shortening and Redirection Service in WordPress [...]

    By Websites You Shouldn´’t Have Missed in August, September 1st, 2008 at 4:11 am

  6. I have another use for shortened URLs that was not in you list. My main use is to keep URLs from wrapping in e-mail.

    I often see the first part of a long URL that I used in a mailing show up in my 404 errors. This is especially true if someone reads the message through Yahoo mail or a link ends up on a Yahoo list. Yahoo just doesn’t seem to be able to wrap long URLs and keep them clickable.

    By Doug Smith, September 1st, 2008 at 8:51 pm

  7. I’d love to have some access to try this out (Qurly.net)…!

    By John, September 1st, 2008 at 9:09 pm

  8. [...] Build Your Own URL Shortening and Redirection Service in WordPress | WebDevLounge | design, developm… - Interesting description of how to build your own URL-redirection service using Wordpress custom fields. (tags: howto wordpress tips tutorial ) Tags: howto · Linky · tips · tutorial · wordpress [...]

    By Links: Build Your Own URL Shortening and Redirection Service in WordPress | WebDevLounge | design, development, SEO and wordpress | articles, discussion and community, September 2nd, 2008 at 10:01 pm

  9. [...] - Build Your Own URL Shortening and Redirection Service in WordPress [...]

    By rss blog » Blog Archive » Websites You Shouldn’t Have Missed in August 2008, September 2nd, 2008 at 10:50 pm

  10. Build Your Own URL Shortening and Redirection Service in WordPress…

    Have you seen those cryptic short URLs popping up everywhere - on web pages and even in Twitter or Plurk? If you build websites, you might wonder, “Why bother?,” especially since all the link juice ends up going to the service instead of to the sou…

    By Leonaut.com, September 4th, 2008 at 12:44 pm

  11. [...] Build Your Own URL Shortening and Redirection Service in WordPress | WebDevLounge | design, developm… Have you seen those cryptic short URLs popping up everywhere – on web pages and even in Twitter or Plurk? If you build websites, you might wonder, “Why bother?,” especially since all the link juice ends up going to the service instead of to the source URL. This article discusses their uses, lists some services, and explains how you can create your own custom version in WordPress. It also covers a few concepts in the tutorial sections: (tags: wordpress urls url service tips tutorials seo short shorturl tiny tutorial tinyurl) Gelesen: 4 · heute: 4 · zuletzt: 06.09.2008 [...]

    By links for 2008-09-05 | hansi.unblogged, September 6th, 2008 at 11:32 am

  12. [...] - Build Your Own URL Shortening and Redirection Service in WordPress [...]

    By Technology Story» Blog Archive » Website You Shouldn’t Have Missed, September 16th, 2008 at 1:12 pm