WordPress: Auto URL Shortening

WP Auto URL ShorteningEveryday there are scores of new links shared, re-tweeted, posted, and emailed by people like you and I. Because of social media platforms like Twitter and Facebook, our love for sharing information, tutorials, freebies, etc., has never been stronger!

The Proposition

As a WordPress developer/designer, how would you like if URLs on your WordPress site were automatically shortened as soon as you publish? This would mean instantly available shortened URLs for sharing/posting AND statistics of your links!

Here’s How

We are going to build the Auto URL Shortening feature within your WordPress theme using the bit.ly API. Let’s start with the functions.php file found within your theme.

The functions.php file is included in most WordPress themes as a place to drop custom functions to be used from the theme. If this file doesn’t exist in the theme you are using, go ahead and create it.

Add 3 functions within the functions.php file

function makeshorturl()
{

}

function shorturl_metabox()
{

}

function showshorturlbox()
{

}

The first function, makeshorturl(), as the name suggests will be creating a short URL for us. The second and the third functions will work together to show us the short URL in the admin editor.

Shortening the link

function makeshorturl()
{
    global $post;

    $short_url = json_decode(file_get_contents('http://api.bit.ly/v3/shorten?login=[username]&apiKey=[apikey]&longURL='.urlencode(get_permalink($post->ID)).'&format=json'));

    if($short_url->status_code=="200")
    {
         $short_url = $short_url->data->url;
    }
    else
    {
        $short_url = "Bit.ly Error! ".$short_url->status_txt;
    }

    do_action('makeshorturl');

    return $short_url;
}

The first line in this function declares WordPress’s global $post variable which holds all the data for the current post. We extract the permalink of the current post using the get_permalink() function and supplying the current post’s id. We then take the permalink and pass it on to bit.ly’s API which returns us a short URL within a JSON object. Next we extract the short URL. If an error occurs we simply return the error.

The do_action() method in WordPress makes this function hookable with other functions/hooks and the function can be used within theme using the hook – makeshorturl().

Want to know more about do_action() and wordpress hooks?

Lets look at the api call in more detail

http://api.bit.ly/v3/shorten?login=[username]&apiKey=[apikey]&longURL='.urlencode(get_permalink($post->ID)).'&format=json

It’s really quite simple.

The login parameter would expect your login over at bit.ly (don’t have one? create one here). The apiKey parameter accepts the API key given to each bit.ly account. If you already have an account you can find the API key here. The longURL parameter expects an encoded long URL string that needs to be shortened, and this is where our custom permalinks get passed. The format parameter expects one of the three values – json, xml or text; depending on the format value specified, the API returns the shortened url (and more data) as JSON, XML or text respectively. By default, if format is not specified, it returns a JSON object. For more info on the bit.ly API, refer the API documentation. Once the bit.ly API sends the JSON object back, we use PHP’s json_decode function to decode the JSON object into a PHP5 object.

Adding the shortened URL to the admin editor

Once the permalink has been shortened, we need to make it available in the backend. To do this, we use the two functions as outlined below.

function shorturl_metabox()
{
    if(is_admin())
    {
        add_meta_box('bitlyurl',__('Short URL','short-url'),'showshorturlbox','post','side');
        add_meta_box('bitlyurl',__('Short URL','short-url'),'showshorturlbox','page','side');
    }
}

The shorturl_metabox will first check if the user is within the admin section of the wordpress based site/blog. Then we add a meta box to the admin page.

Short URL Admin A Meta box in WordPress basically is a box which sets and gets meta information about a post. Default meta boxes include Post Tags, Discussions and so forth.

More on meta boxes.

The add_meta_box function takes five parameters:

  1. the HTML id of the box
  2. the label/title of the box
  3. the callback function which would render the box contents
  4. the type of write screen – post or a page
  5. the position or context where the box would be located – Normal, Advanced or Side.

More on add_meta_box().

As you can see, that when the function “adds” the meta box to the admin view, it calls the showshorturlbox function which renders the contents of the meta box, as shown below.

function showshorturlbox()
{
    echo '<label for="bitlyurl">'.__('Shortened URL','short-url-label').': '.makeshorturl().'</label><br/><br/>';
}

The function echoes the short URL in a label, thus making it available to be shared by the authors of the post/page. We are calling makeshorturl() which fetches or generates the shortened URL via the bitly API.

Bringing it together

Finally we use the following three lines which attach our makeshorturl() function to the publish_post and publish_page hooks and attaches shorturl_metabox to the do_meta_boxes hook that generates the meta boxes.

add_action('publish_post','makeshorturl');
add_action('publish_page','makeshorturl');
add_action('do_meta_boxes','shorturl_metabox');

Complete Code within functions.php

function makeshorturl()
{
global $post;

$short_url = json_decode(file_get_contents('http://api.bit.ly/v3/shorten?login=[username]&apiKey=[apikey]&longURL='.urlencode(get_permalink($post->ID)).'&format=json'));

if($short_url->status_code=="200")
    {
         $short_url = $short_url->data->url;
    }
    else
    {
        $short_url = "Bit.ly Error! ".$short_url->status_txt;
    }
    do_action('makeshorturl');
    return $short_url;
}

function shorturl_metabox()
{
    if(is_admin())
    {
        add_meta_box('bitlyurl',__('Short URL','short-url'),'showshorturlbox','post','side');
        add_meta_box('bitlyurl',__('Short URL','short-url'),'showshorturlbox','page','side');
    }
}

function showshorturlbox()
{
    echo '<label for="bitlyurl">'.__('Shortened URL','short-url-label').': '.makeshorturl().'</label><br/><br/>';
}

add_action('publish_post','makeshorturl');
add_action('publish_page','makeshorturl');
add_action('do_meta_boxes','shorturl_metabox');

Usage

If you did like to show off the shortened URL to your users simply insert this code where you want the short URL to show up:

<?php echo makeshorturl(); ?>

BONUS

Want a ready-to-use solution? Here’s the plugin version of the above code that will generate the shortened URLs on the fly for you to share. If you did like to call the functions from within the theme template, you can do so by using:

<?php echo wps_hook(); ?>

Note: Above tag is for the plugin only.

PS: The plugin can also show number of clicks on a shortened link :) per shortened URL

Download it!

Download Plugin - WP Short URL Maker

Manoj “Designerfoo(tm)” Sachwani is a freelance webmaster and runs a small webdesign/webdevelopment shop. He builds websites with an edge. Connect via Twitter or website

 

If you liked this article, please help spread the news on the following sites:

  • Bump It
  • Blend It
  • Bookmark on Delicious
  • Stumble It
  • Float This
  • Reddit This
  • Share on FriendFeed
  • Clip to Evernote