Build Internet has a brand new theme, and that's only the beginning. Read the full story or hide this bar

Automatically Shorten URL on Page Load in WordPress

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.

Wordpress.com stats not installed! Posted Tuesday, April 6th, 2010 / Back to Top

I this post. Tweet
SPONSOR

21 Comments 9 Mentions

  1. Markus Thömmes Author Editor

    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.

    April 6, 2010 · Reply

  2. Armin C. Author Editor

    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 :)

    April 7, 2010 · Reply

  3. kucrut Author Editor

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

    April 7, 2010 · Reply

  4. Jennifer Shea Author Editor

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

    April 8, 2010 · Reply

  5. Nikola Author Editor

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

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

    April 9, 2010 · Reply

  6. Peter Wilson Author Editor

    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.

    April 10, 2010 · Reply

  7. NewGadgetz Author Editor

    Really handy tip. Thanks!

    April 12, 2010 · Reply

  8. Cook Author Editor

    good article….nice useful information

    April 18, 2010 · Reply

  9. Brett Widmann Author Editor

    This is a great article. Thanks for sharing.

    December 10, 2010 · Reply

  10. rigobcastro Author Editor

    Great tutorial, thanks for sharing it!

    December 29, 2010 · Reply

  11. Michae Author Editor

    Great post. I’ve done it already, but my code seemed bulkier, so I’m gonna use thise. Thanks a bunch.

    January 27, 2011 · Reply

  12. Kpop Flash Author Editor

    thanks for the great tutorial :)

    March 10, 2011 · Reply

  13. suntradetop Author Editor

    To see a world in a grain of sand. And a heaven in a wild flower
    Hold infinity in the palm of your hand . And eternity in an hour

    June 1, 2011 · Reply

  14. David Proctor Author Editor

    @armin – How would you apply those changes to the functions.php? Thanks.

    September 25, 2011 · Reply

  15. http://Youtu.be/ Author Editor

    hi!,I really like your writing so a lot! proportion we be in contact more about
    your article on AOL? I need a specialist in this house to
    unravel my problem. Maybe that is you! Taking a look ahead to see you.

    Also visit my blog – http://Youtu.be/

    February 25, 2013 · Reply

  16. view more about Author Editor

    You need to take part in a contest for one of the best websites on the internet.
    I will recommend this site!

    March 6, 2013 · Reply

  17. brad Author Editor

    Can’t get the code to work. Error on the following:

    Any ideas? I’ve tried using ‘ ‘ and ” ” as well.

    Objective is to get a bitly link for an author archieve rather than a post. Older functions depreciated. Not sure how to make it work. I’m hoping your code with get_permalink will work.

    Thanks for your help

    March 12, 2013 · Reply

  18. Motorbikes Author Editor

    I have to convey my respect for your kindness for all those that require guidance on this one field.

    Your particular commitment to passing the remedy up and down
    has been incredibly functional and has continually empowered
    many people just like me to attain their dreams. Your amazing insightful information entails significantly to me and specially to
    my peers. Thanks a ton; from all of us.

    March 16, 2013 · Reply

  19. Immigration Advicers in Tottenham Author Editor

    Way cool! Some very valid points! I appreciate you penning
    this post plus the rest of the website is very good.

    My site … Immigration Advicers in Tottenham

    March 19, 2013 · Reply

  20. Immigration Solicitors in Ilford Author Editor

    Please let me know if you’re looking for a article author for your weblog. You have some really great articles and I believe I would be a good asset. If you ever want to take some of the load off, I’d really like
    to write some articles for your blog in exchange for a link back
    to mine. Please send me an e-mail if interested.

    Thank you!

    March 20, 2013 · Reply

  21. engagement rings cheap in memphis Author Editor

    There is definately a lot to find out about this issue.

    I love all the points you made.

    April 22, 2013 · Reply

 

Join the Conversation

Back to Top / Comment RSS

2012 Build Internet. Created by One Mighty Roar. Icons by Komodo Media. Back to Top