Automatically Shorten URL on Page Load in WordPress

A few weeks back, we posted a tutorial using the Bit.ly API and Twitter in order to share feedback on a blog post. Since the original post went up, we’ve spent some time revisiting this idea for Build Internet’s upcoming theme redesign.

In this post we’ll expand on the original tutorial by automating the link shortening process one step further for use in WordPress. By the end of the post you will have a fully automatic link shortening system for all posts in your WordPress installation.

What’s Wrong With the Original?

The original example used a combination of David Walsh’s Bit.ly shortening script and jQuery to compose the a tweet plus feedback. If you need to refresh your memory, take a look at the original demo page before continuing on.

The Original Feedback Demo

Just to be clear, there isn’t really anything wrong with the original tutorial. We can, however, make it more useful by adding a few features to make WordPress integration a “set it and forget it” operation.

With this version, we will only generate a short URL if it does not already exist for the current page. Once they are generated, a post’s short URL will be stored in the post meta for future page loads. Each post will only interact with the bit.ly API once in its lifetime.

A Side Note: WordPress already has a built-in URL shortening service with the “Get Shortlink” button in the post editor. Even though it’s convenient for a quick link, the lack of API makes theme development difficult. Viva la bit.ly API.

Shorten URL Script

This version of David Walsh’s script has been modified to only require one argument. Since most blogs will use the same account for all links, the API credentials are defined within the function. Insert or include the code below in your WordPress theme’s function.php file. Remember to replace the bit.ly credentials with your own API key and username.

<?php

	/*
		Based on code from David Walsh

http://davidwalsh.name/bitly-php

	*/

	function make_bitly_url($url,$format = 'xml',$version = '2.0.1')
	{

		//Set up account info
		$bitly_login = 'YOUR LOGIN HERE';
		$bitly_api = 'YOUR API KEY HERE';

		//create the URL
		$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$bitly_login.'&apiKey='.$bitly_api.'&format='.$format;

		//get the url
		$response = file_get_contents($bitly);

		//parse depending on desired format
		if(strtolower($format) == 'json')
		{
			$json = @json_decode($response,true);
			return $json['results'][$url]['shortUrl'];
		}
		else //For XML
		{
			$xml = simplexml_load_string($response);
			return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
		}

	}

?>

Once the script has been added to your theme, you can use the function below to return a shortened bit.ly link for the current post URL.

In the next step, we’ll take the load off of bit.ly by storing the shortened URL for future pageviews.

Save URL to Post Meta

Saving to a post’s meta information is surprisingly simple. In the interest of efficiency, we want the bit.ly API call to only happen if no short URL has been made for the post being loaded. To do this, we’ll make a standard case statement inside the post loop of single.php in your theme files. Copy in the code below right under the start of your post loop, and then meet back below for an explanation.

<?php

	//Check for post's shortened URL. Used with twitter feedback.
	if(get_post_meta($post->ID, "short_url", true) != ""){ 

		//Short URL already exists, pull from post meta
		$short_url = get_post_meta($post->ID, "short_url", true);

	}else{

		//No short URL has been made yet
		$full_url = the_permalink();
		$short_url = make_bitly_url($full_url);

		//Save generated short url for future views
		add_post_meta($post->ID, 'short_url', $short_url, true);
	}

?>

This case statement says “If this post’s meta information has a short url saved, assign it to the $short_url variable. If it doesn’t, use the post permalink to make a shortened link and save it to the post meta.” Since each post should only have one shortened URL, the “unique” argument in get_post_meta is set to true.

Once the URL has been established, you can display it throughout your template using:

<?php echo $short_url; ?>

Automated Links

With this method in place, you shouldn’t have to worry about creating short links for all of your posts. A simple pageview will trigger the action, which leaves you plenty of time to find new and creative ways to share the content. Automation is good like that.

If we’ve left anything out, made an error, or explained something poorly, please leave a comment below and we’ll try to sort it out! If you can think of any creative uses for this type of system, we’d love to hear that too.

  • Stumble It!
  • Bookmark It!
  • Tweet it!

About Zach Dunn

Zach is a partner and interface designer at One Mighty Roar from Massachusetts, USA. Follow him on Twitter @zachdunn.

 

Discussion

  1. Markus Thömmes

    April 6th, 2010 at 1:49 PM

    And now to push this one to perfection, can’t we use a hook to fire the function on publishing the post, so the user will never have any speed problems.

  2. Armin C.

    April 7th, 2010 at 6:39 AM

    Nice upgrade on the previous tut, but why not move some of that code into the functions.php and make the theme file less clunky?

    re:Markus : That would probably be a smart move to reduce server load

    p.s.:keep up the good work Zach :)

  3. kucrut

    April 7th, 2010 at 5:02 PM

    Shouldn’t you use get_permalink() for the $full_url var? the_permalink() will echo the url.

  4. Jennifer Shea

    April 8th, 2010 at 1:43 PM

    Can I do that but don’t short the URL when the message is under 140 characters?

  5. Nikola

    April 9th, 2010 at 9:30 AM

    why re u not using the new bit.ly api?

    btw. check this shortener – http://0.mk

  6. Peter Wilson

    April 10th, 2010 at 2:33 AM

    I’d probably keep the short url hidden from post editors by naming it _short_url (note the underscore prefix).

    Of course, hiding the custom data prevents editors from changing the short url if they wish to, for example, use a different bit.ly account.

  7. NewGadgetz

    April 12th, 2010 at 7:47 PM

    Really handy tip. Thanks!

  8. Cook

    April 18th, 2010 at 9:24 AM

    good article….nice useful information

Join the Conversation!

Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.

CommentLuv is Enabled

 

Sponsors

Advertise on Build Internet!