Use WordPress as a Custom URL Shortener

Take Back Control from Goo.gl, Bit.ly, and WP.me

Want to share this tutorial? Use this link: https://z13.me/WPURLS

Want a custom URL shortener but don't like to code?

Introduction

We’ve all seen them: behemoth URLs that are simply too unwieldy to paste anywhere. Who would want to paste this beast into a social media update?

https://www.washingtonpost.com/news/speaking-of-science/wp/2016/12/21/a-supervolcano-caused-the-largest-eruption-in-european-history-now-its-stirring-again/?hpid=hp_hp-more-top-stories_sos-volcano-200pm%3Ahomepage%2Fstory&utm_term=.5c4529e37ac8

Weighing in at a hefty two hundred and forty-four characters (this paragraph is only two hundred and eighty-five), that URL wouldn’t even fit into some services. In essence, you have to shorten it just to be able to use it. Of course, you have options when it comes to shortening URLs.

Already know exactly why you’re here and don’t like options?

List of Options

# Mini-Review Link Example
1. zURLs Visit:
zURLs
Example:
https://z13.me/WPURLS
2. Goo.gl Visit:
Goo.gl
Example:
https://goo.gl/WN524i
3. YOURLS Visit:
YOURLS
Example:
N/A (No Test Site)
4. Bitly Visit:
Bitly
Example:
http://bit.ly/2h7m34g
5. Ow.ly Visit:
Ow.ly
Example:
http://ow.ly/7DZM307oeLG
6. is.gd Visit:
is.gd
Example:
https://is.gd/DWY7Ul
7. shorte.st Visit:
shorte.st
Example:
http://viid.me/qtuNXV
8. t.co Visit:
t.co
Example:
https://t.co/biYknG9Gtp
9. TinyURL Visit:
TinyURL
Example:
http://tinyurl.com/hx2qzmz

URL Shortening Options

There are a lot of options out there when it comes to shortening URLs. This tutorial includes a brief review of eight of the most popular, and one new one: zURLs. Which one is best for your situation depends on what features you need and what goals you have in mind.

Each review runs through the overall features of the URL shortening service, the cost, whether or not the service supports changing link destinations (many do not!), whether or not the service supports analytics and (if so) what kind, and the complexity of setting up the service and using its features. Most of the options are hosted by third parties and do not allow full access to users. Only two options allow full control: zURLs and YOURLS.

After the mini-reviews, this tutorial runs through a way to create your own custom URL shortener using WordPress and the Redirection plugin. Not only does having your own URL shortener give you more control over your links, it also means that you won’t be reliant on a third party (e.g., while unlikely, Bitly could go out of business tomorrow, leaving you high and dry and your links completely useless). In addition to zURLs, ZCS offers a self-hosted solution.

If you want to have not just your own URL shortener but also your own server on which to run it, click here to take a look at ZCS’s personal URL shortener service.

zURLs

Overall
It may be the newest entry on this list, but zURLs is fully functional and offers features with which only the most expensive paid plans can compete. Not only does zURLs support changing your link destinations (the number one requested feature for link shorteners), it also comes with full integration for Google Analytics so you can analyze every click your links receive. Further, zURLs comes with free SSL/TLS support (courtesy of Let’s Encrypt) for all domains/users, and support for building your links using regular expressions (aka regex).

At $99 per year, zURLs is also probably the most affordable of the paid options (compare with Bitly’s plans starting at $495/$995 per month and HootSuite’s plans that go from $9.99 per month to $99.99 per user per month). Of course, you’ll also have to register your own domain, but that means you’ll remain in complete control. A domain name will probably cost between $2 and $20 (depending on which TLD you pick). For the price, you won’t find a better option than zURLs.

  • Features [Overall] 100%
  • Cost 30%
  • Change Link Destinations 100%
  • Analytics 100%
  • Simplicity 90%

Pros

  • SSL/TLS
  • Customizable
  • Link Destinations Can Be Changed/Update
  • Extensive Analytics

Cons

  • Not Free

Goo.gl

Overall
Goo.gl, as the name strongly implies, is Google’s URL-shortening service. For a company that essentially owns Internet search, advertisements, and analytics, Goo.gl is a rather disappointing service. It will shorten links and it does provide some analytics (country, platform, browser, referrer, and total clicks), but these are much more limited than what you would have available if you were using Google Analytics (which Google seemingly decided not to do).

For some users, this might be enough information, but there are no configuration options and the service is limited. It is, however, free.

  • Features [Overall] 40%
  • Cost 0%
  • Change Link Destinations 0%
  • Analytics 50%
  • Simplicity 100%

Pros

  • SSL/TLS
  • Free
  • Basic Analytics Built In

Cons

  • Google (they have a history of killing projects with no warning)
  • No Configuration Options
  • Analytics Are Quite Basic

YOURLS

Overall
This is the only other service on the list that compares with the customizability and feature set of zURLs (not counting the custom solution at the end of this article). However, this comes with one very important caveat: YOURLS will require you to do some coding. YOURLS, like the custom solution at the end of this article, is truly roll your own.

In order to use YOURLS, you will need to set up a server with a handful of requirements (MySQL, PHP, et cetera). Once you have your server set up, installing YOURLS is straightforward and should take no more than ten minutes (assuming you’ve done a bit of coding). Once installed, YOURLS is fairly simply: You log in to the backend and add links. You can change link destinations and you can use Google Analytics (with a bit of configuring). Overall, YOURLS offer roughly the same feature set as zURLs, though in a much less convenient package. Further, while YOURLS is free, the server on which you’ll have to install it probably won’t be.

  • Features [Overall] 90%
  • Cost 30%
  • Change Link Destinations 100%
  • Analytics 80%
  • Simplicity 10%

Pros

  • Customizable
  • Support for Google Analytics (with some configuration)
  • Technically “Free” (see Cons)

Cons

  • Requires Coding
  • Requires You to Maintain a Server
  • Ongoing Server Costs

Bitly

Overall
Bitly. It would be difficult to overstate Bitly’s influence in the URL-shortening market. While TinyURL, infra, was one of the first, Bitly came shortly afterward and quickly became the eight-hundred-pound gorilla. Bitly’s basic service is free, fast, and reliable. It is, however, also limited. If you want anything beyond basic analytics (clicks, referral information, and geographical information), then you’ll have to sign up for one of Bitly’s very expensive paid plans (nearly $12,000 per year for their “Growth” plan).

By default, shortlinks are HTTP (i.e., not SSL/TLS), and you cannot change link destinations. Further, you are limited to using bit.ly (this is the same with most options on this list, with the notable exceptions being zURLs, YOURLS, and the custom solution) unless you sign up for a paid plan. If you’re okay with basic analytics and little control, Bitly is an acceptable solution.

  • Features [Overall] 70%
  • Cost 80%
  • Change Link Destinations 0%
  • Analytics 50%
  • Simplicity 90%

Pros

  • Free Option
  • Recognizable Links
  • Quick and Reliable

Cons

  • Very Expensive Paid Plans
  • No Custom Domain (on Free Plan)
  • No SSL/TLS by Default
  • Cannot Change Link Destinations

Ow.ly

Overall
Ow.ly is part of HootSuite, a social media-management and analytics platform. When coupled with HootSuite, Ow.ly provides powerful analytics and insights into your links and their traffic. Of course, this comes at a price: from $9.99 per user per month to $99.99 per user per month.

While HootSuite does have a free plan (and you’ll need to sign up for it if you want to access any information about your shortened links), they definitely push customers to their paid plans. As with most services, you cannot change your link destinations with Ow.ly. Overall, Ow.ly doesn’t make sense unless you sign up for HootSuite, but it’s a great tool if you are managing a serious social media presence and need the power that the full HootSuite offers.

  • Features [Overall] 70%
  • Cost 70%
  • Change Link Destinations 0%
  • Analytics 60%
  • Simplicity 60%

Pros

  • Basic Analytics (requires account)
  • Free (paid plans optional)
  • Deep Integration with HootSuite

Cons

  • Paid Plans Can Be Expensive
  • Cannot Change Link Destinations
  • Most Features Restricted to Paid Accounts

is.gd

Overall
This option is a project created and hosted by the good people over at Memset. Memset provides a number of free utilities, is.gd being one of the better known among them. While its page may be simple (and have a slightly out-of-date design), is.gd has a good feature set.

First, all links produced by is.gd are HTTPS (i.e., SSL/TLS); this is important as more and more of the Web moves to SSL/TLS (and Google has begun to ‘force’ the transition). Second, is.gd provides fairly good analytics (clicks, country, browser, platform, day of the week, hour of the day). However, that’s about all the service offers. You cannot change link destinations (though you can pick your URLs initially, if they’re available), and you cannot customize much of anything. Also, be careful to expand the options when creating a link with is.gd, statistics are not collected by default.

  • Features [Overall] 80%
  • Cost 0%
  • Change Link Destinations 0%
  • Analytics 70%
  • Simplicity 100%

Pros

  • Quick, Reliable, and SSL/TLS Secured
  • Basic Analytics (not by default)
  • Free

Cons

  • No Configuration Options
  • Only Basic Analytics
  • Cannot Change Link Destinations

shorte.st

Overall
This option is included primarily because many people will encounter these links. However, it is not recommended to use shorte.st as it has a rather unsavory reputation. If you want to shorten links in order to scam or to spam people, use shorte.st (n.b., do not actually do this).

Seriously, don’t even click the example URL. This shortener is one of the worst of the worst when it comes to interstitial ads (i.e., those annoying ads that appear before you’re actually redirected to your destination). It’s free and probably offers some analytics, but I cannot bring myself to create an account to verify the features. Included simply for the sake of completeness (and warning).

  • Features [Overall] 0%
  • Cost 0%
  • Change Link Destinations 0%
  • Analytics 0%
  • Simplicity 10%

Pros

  • Free

Cons

  • Unsavory
  • Intrusive Advertising
  • Disreputable

t.co

Overall
Another option in the “included for completeness” category, t.co isn’t actually an option. This domain is used by Twitter to shorten links so that tweets stay within their character limits. Undoubtedly, most people have come across a t.co shortlink at some point. Well, this is the domain that creates them and now you know why.

  • Features [Overall] 10%
  • Cost 0%
  • Change Link Destinations 0%
  • Analytics 0%
  • Simplicity 100%

Pros

  • Free

Cons

  • Restricted to Twitter

TinyURL

Overall
One of the original (and longest lived) of the URL shorteners, TinyURL has the basic feature set you would expect, with one exception: analytics. If you want to know how many clicks your links are getting (or anything about those clickers), then you’ll want to pick something other than TinyURL.

It is also worth noting that there have been controversies in the past concerning TinyURL’s alleged practice of rewriting affiliate links. Overall, there’s no real reason to use TinyURL instead of one of the better options.

  • Features [Overall] 40%
  • Cost 0%
  • Change Link Destinations 0%
  • Analytics 0%
  • Simplicity 100%

Pros

  • Free
  • Recognizable

Cons

  • No Analytics
  • Very Low Configurability
  • Possible Questionable Practices

Tutorial: Creating a Personal URL Shortener Using WordPress

For this tutorial, we’re going to assume that you’ve already installed WordPress (single site or Multisite doesn’t matter) and have the appropriate permissions to install plugins. First, install Redirection. This plugin will be doing all of the heavy lifting in our system.

Once you’ve installed and activated Redirection, you’ll find its settings under Tools Redirection. Once in the settings for Redirection, you’ll see a handful of options:

Redirections | Groups | Modules | Log | 404s | Options | Support

Click Options. Choose how long you want to keep your Redirect and 404 logs (n.b., keeping logs for too long will almost certainly start to bog down your database server). Type $hex$ into the “Auto-generate URL” box (not necessary, but good practice). Make sure to save (“Update”) your options.

That’s it. You’re done. No, really. You’ll probably want to do a bit more configuration (and familiarize yourself with regex), but you’ve now got a fully functional URL redirecting (and shortening, if you have a ‘good’ domain) service).

Redirects
This is where all of your redirects are listed. This is also where you create new redirects. As you can see, you have several options when configuring redirects. With few exceptions (power users, et alii), you’ll use “URL only” for the match and “Redirect to URL” for your redirects. Whether or not you use regex depends entirely upon your comfort level with regex (and the needs of the redirects you’re creating). (Read more about regex by clicking through the links under Resources.)

Groups
Groups are simply used for organizing your redirects. If you intend to have a lot of redirects, save yourself future headaches and plan out your grouping in advance. Unless you really know what you’re doing, just stick with WordPress groups (both Apache and Nginx require server configuration that is beyond the scope of this tutorial).

Modules
Ignore this. One of the primary points of creating this custom URL shortener/redirector was to have good access to analytics data. Neither Apache- nor Nginx-based Redirection configurations will track hits (unless you’ve configured something at the server level, but then you wouldn’t need this tutorial).

Logs
This is self-explanatory. You can export to CSV (for analysis in external software or for archival purposes). If you set a retention policy of ‘forever’ in the Options, you can use “Delete All” at the bottom of this page to purge your logs (and unburden your server).

404s
This page will prove much more useful than you may imagine. Visit it frequently to see what URLs visitors are trying (and failing) to reach on your site. Use this information to create redirects to send those would-be 404s somewhere useful.

Analytics

Wait a minute! This URL shortener/redirector doesn’t have any analytics yet. Good catch. If you haven’t done so already, go sign up for a Google Analytics account. Next, install a Google Analytics plugin from the WordPress plugin repository. There are several good ones. Personally, I use (and highly recommend) Google Analytics+ from WPMU DEV. It’s not free, but it’s a great plugin.

Once you’ve activate and configured your Google Analytics plugin of choice, you’re good to go.

Changed your mind and want the options back?

%

Free

%

WordPress

%

Control

%

Configurability

Resources

Since you’re apparently the enterprising type who isn’t worried about delving into a bit of code, you might find these useful:

These are three of the best tools (order not accidental) for testing your regex. If you want to get the most out of your new URL shortener, you’ll want to learn a bit of regex.

WordPress
HTML5
CSS3-Shield
CSS3
PHP
jQuery
Code
Link

Tutorial: Statistics Page

Now that you have your custom URL shortener up and running, let’s make a statistics page so you can view your (basic) analytics data from the frontend. We’ll proceed in four steps:

  1. Obtain a bit of necessary information from the database.
  2. Create the statistics page template.
  3. Style the statistics page with a bit of CSS.
  4. Make the data on the statistics page sortable using a jQuery library.

Step 1. Database Information

In order to create the statistics page, we’ll need to know in which database table Redirection is storing its information. This information will always be in wp_redirection_items if you’re using WordPress as a single-site install. If, however, you have a MultiSite install, you’re going to need to figure out the ID number of the site on which you installed redirection. Just navigate to the Sites menu in the Network Admin, hover over your site, and take a look in the status menu. You’ll see “id=#” at the end of the URL, # is your site’s ID. Drop that into this pattern: wp_#_redirection_items. That’s it, we’re ready for Step 2.

Step 2. Creating the Statistics Page Template

We are going to be using a page template for our statistics page. My personal shortener/redirector and zURLs both use Twenty Twelve. I highly recommend the use of Twenty Twelve (or a similarly simple theme). If you happen to be using your actual site as your shortener/redirector, then you’ll almost certainly be using a different theme (and you’ll need to modify the template, infra, accordingly).

Here’s the code for the statistics page template:

<?php /* Template Name: Redirection Stats */ ?>
<?php get_header(); ?>

	<div id="primary" class="site-content">
		<div id="content" role="main">

			<?php while ( have_posts() ) : the_post(); ?>
				<h1>Redirection Statistics</h1>
				<?php

						if (is_user_logged_in()):

						global $wpdb;
						$wp_2_redirection_items = $wpdb->get_results("SELECT * FROM wp_2_redirection_items;");

						echo '<table id="redirection-statistics" class="tablesorter">';
							echo '<thead>';
								echo '<tr>';
									echo '<th>Regex</th>';
									echo '<th>Hits</th>';
									echo '<th>Last Access</th>';
									echo '<th>Destination URL</th>';
								echo '</tr>';
							echo '</thead>';
							echo '<tbody>';
							foreach($wp_2_redirection_items as $url)
							{
								echo '<tr>';
									echo '<td>'.$url->url.'</td>';
									echo '<td>'.$url->last_count.'</td>';
									echo '<td>'.$url->last_access.'</td>';
									echo '<td>'.$url->action_data.'</td>';
								echo '</tr>';
							}
							echo '</tbody>';
						echo '</table>';

						else:
					echo 'This page is restricted to registered users.';
					endif;

				?>
<script type="text/javascript">		
jQuery(document).ready(function($)
	{
		$("#redirection-statistics").tablesorter(); 
	}
);
</script>
			<?php endwhile; // end of the loop. ?>

		</div><!-- #content -->
	</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

The really important bit, as you’ve probably guessed, is the PHP in the middle (lines nine through forty-two). This code does two things: 1) it checks if the current user is logged in (and prints a message if not) and 2) pulls Redirection’s data from the database and builds a table with it. This table is what we’ll be styling in the next step. You can edit these queries to pull more or less data, change the <th></th> elements to rename columns, and edit the “This page is restricted to registered users.” text without any worries of ‘breaking’ the code.

Once you’ve created this template, log in to your WordPress website. Create a new page and select the “Redirection Stats” page template. That’s it. You don’t need to add any content to the page. Publish the page and take a look at it on the frontend. Just refresh the page whenever you’d like to see your current Redirection statistics.

Step 3. Styling the Statistics Page with CSS

This part is primarily a matter of taste. However, that being said, much of the CSS included in this tutorial, infra, is actually designed to make the table more readable/usable. If you want it to be ‘pretty’, you’ll probably have to do some additional design work.

Drop the following CSS into your theme in whatever way you prefer (ideally, through a proper enqueueing in functions.php or inclusion in your child theme’s style.css):

body.page-template-page-redirection-stats #main, body.page-template-page-redirection-stats #primary {
	margin: 0;
}

table#redirection-statistics {
	width: 100% !important;
}

table#redirection-statistics, #redirection-statistics th, #redirection-statistics td {
	border: 1px solid black;
	border-collapse: collapse;
	vertical-align: middle;
	padding: 0.5em;
}

table#redirection-statistics th {
	background-color: #000000;
	color: #ffffff;
}

table#redirection-statistics tr:hover {
	background-color: #aaaaff !important;
}

table#redirection-statistics tr:nth-child(even) {
	background-color: #f2f2f2;
}

This CSS will, in short, create a greyscale table with a white-text-on-black-background header and a table of alternating white and grey rows. Additionally, hovering over a row will highlight it. Here’s a sample:

Statistics Table Preview

Step 4. Making the Table Sortable with jQuery and tablesorter

You now have a table on the frontend of your site (accessible only to logged-in users) that displays your redirects and basic analytics information. However, this table isn’t sortable, which limits its utility. Let’s fix that.

Head over to the tablesorter page and download tablesorter (a jQuery plugin). Upload the script to your site, and then enqueue it in your child theme (you are using a child theme, right?). If you need jQuery, enqueue that, too.

Example Enqueueing of jQuery and tablesorter

function jquery_3() {
	wp_enqueue_script('jquery-3', '//code.jquery.com/jquery-3.1.1.js',false,null);
}
add_action('wp_enqueue_scripts', 'jquery_3');

function jquery_tablesorter() {
	wp_enqueue_script('jquery-tablesorter', '/wp-content/scripts/jquery.tablesorter.js',false,null);
}
add_action('wp_enqueue_scripts', 'jquery_tablesorter');

Once you’ve uploaded the script and enqueued it in your functions.php file, you should be good to go. Clear all your caches and test out your new, sortable statistics table.

Conclusion

Overall, having control over your own URL shortener/redirector is great. You don’t have to worry about a third party going out of business (or simply losing your data); you can change settings and configurations as frequently (or as infrequently) as you like; you can change link destinations whenever necessary or desired; and you can collect granular analytics data so you know everything about the traffic hitting your links. This article gives you three great options:

  1. zURLs — the best option for those who just want it to work and don’t want to mess around with any code.
  2. Professional Setup — the best option for those who want complete control, from the server up, but don’t want to mess with any code.
  3. A Custom URL Shortener/Redirector — the best option for those who want full control and don’t mind digging into a bit of code.

Pick whichever option best fits your needs. Have a question? Feel free to visit us over on our forums or send us an email.