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.

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.

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:

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.

Posted Tuesday, April 6th, 2010 · Back to Top

SPONSOR

Add Comment

23 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.

    ·

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

    ·

  3. kucrut Author Editor

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

    ·

  4. Jennifer Shea Author Editor

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

    ·

  5. Nikola Author Editor

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

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

    ·

  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.

    ·

  7. NewGadgetz Author Editor

    Really handy tip. Thanks!

    ·

  8. Cook Author Editor

    good article….nice useful information

    ·

  9. Brett Widmann Author Editor

    This is a great article. Thanks for sharing.

    ·

  10. rigobcastro Author Editor

    Great tutorial, thanks for sharing it!

    ·

  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.

    ·

  12. Kpop Flash Author Editor

    thanks for the great tutorial :)

    ·

  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

    ·

  14. David Proctor Author Editor

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

    ·

  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/

    ·

  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!

    ·

  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

    ·

  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.

    ·

  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

    ·

  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!

    ·

  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.

    ·

  22. zquiet Author Editor

    Does your site have a contact page? I’m having problems locating it but, I’d
    like to send you an email. I’ve got some ideas for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it grow over time.

    ·

  23. people.tribe.net Author Editor

    Whether or not, rather than just steal or manipulate data.
    So, that’s what his Wikipedia page doesn’t ven mention computer
    vision. By etting a setor cop of a hard drive you
    use every day. It’s all put together in just the right way.
    It said the business had made bogus promises that it could secure them refunds.

    ·

 

Build Internet by One Mighty Roar. Since 2008.