Using Google's URL Shortener (goo.gl) in WordPress

The Google URL Shortener API has been released this week so I came up with a short snippet that generates short goo.gl URLs. The script is quite simple, you can paste it in your theme’s functions.php file or create a plugin out of it, so without further ado:

function googl_shortlink($url, $post_id) {
	global $post;
	if (!$post_id && $post) $post_id = $post->ID;

	if ($post->post_status != 'publish')
		return "";

	$shortlink = get_post_meta($post_id, '_googl_shortlink', true);
	if ($shortlink)
		return $shortlink;

	$permalink = get_permalink($post_id);

	$http = new WP_Http();
	$headers = array('Content-Type' => 'application/json');
	$result = $http->request('https://www.googleapis.com/urlshortener/v1/url', array( 'method' => 'POST', 'body' => '{"longUrl": "' . $permalink . '"}', 'headers' => $headers));
	$result = json_decode($result['body']);
	$shortlink = $result->id;

	if ($shortlink) {
		add_post_meta($post_id, '_googl_shortlink', $shortlink, true);
		return $shortlink;
	}
	else {
		return $url;
	}
}

add_filter('get_shortlink', 'googl_shortlink', 9, 2);

For the tech people I’ll explain what I’m trying to do here. So first of all we don’t want to shorten links on draft posts as that could be a waste of resources, so we return an empty string. The magic with get_post_meta and add_post meta in the middle and at the end of the function are done for caching purposes — we don’t want to send too many requests to the Google API so let’s keep the already shortened links in the post’s custom fields. This may be annoying in the UI so you might want to add an underscore in the meta key (“_googl_shortlink”) which will make it invisible to the UI.

Next up, I retrieve the permalink of the published post, since we don’t want to shorten an already shortened URL which is that ugly one by WordPress. I use that permalink in an HTTP request to Google’s API using WordPress’ WP_Http object. Note that I’ve added the Content-Type header, which is required by Google, otherwise it’ll return an error. I decode the result body using json_decode (you need PHP 5.2 or later to do this) and if there’s a valid id, which is the shortened URL, I save it to the post’s meta and return the shortlink. If something went wrong, I return the original WordPress’ short URL.

So, clicking on the “Get Shortlink” button in your admin UI will now produce a Goo.gl shortened link to your post. Neat eh? You can also use short links in your theme, somewhere in The Loop:

echo "Shortlink: " . wp_get_shortlink();

Goo.gl Analytics

Right, you might want to see your short links’ analytics at some point. Well, Goo.gl shortened links are all public and their analytics are public too, so all you have to do is browse to goo.gl/info/code where code is the 5-6 alphanumeric digits attached to your shortened URL at the end.

For convenience I wrote a little snippet that would output the short URL and a link to it’s analytics page in your posts list screen inside the admin panel. Below is the code that should go to your functions.php file or plugin file:

function googl_post_columns($columns) {
	$columns['shortlink'] = 'Shortlink';
	return $columns;
}

function googl_custom_columns($column) {
	global $post;
	if ('shortlink' == $column)
	{
		$shorturl = wp_get_shortlink();
		$shorturl_caption = str_replace('http://', '', $shorturl);
		$shorturl_info = str_replace('goo.gl/', 'goo.gl/info/', $shorturl);
		echo "<a href='{$shorturl}'>{$shorturl_caption}</a> (<a href='{$shorturl_info}'>info</a>)";
	}
}

add_action('manage_posts_custom_column', 'googl_custom_columns');
add_filter('manage_edit-post_columns', 'googl_post_columns');

I wrote about custom columns in a post called Custom Post Types in WordPress 3.0, which should give you a general idea of what’s going on here. For more details visit the WordPress Codex.

That’s about it! Yeah, I know there’s some stuff that can be improved here, like smooth error handling, but it’s up to you to implement it. For more info check out the Google URL Shortener Getting Started page. A good place for experiments with Google’s APIs is Google APIs Console.

The plugin-version of this code is available at the WordPress plugin directory: Goo.gl for WordPress. Thank you for reading and retweeting ;)

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.

18 comments