Using Google's URL Shortener ( in WordPress

The Google URL Shortener API has been released this week so I came up with a short snippet that generates short 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('', 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 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(); Analytics

Right, you might want to see your short links’ analytics at some point. Well, shortened links are all public and their analytics are public too, so all you have to do is browse to 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('', '', $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: for WordPress. Thank you for reading and retweeting ;)

18 thoughts on “Using Google's URL Shortener ( in WordPress

  1. Tweets that mention Using Google’s URL Shortener ( in WordPress --

  2. » Blog Archive » Using Google’s URL Shortener ( in WordPress

  3. Great work kovsheni just was surprised that my first result was a url you use the same wp_get_shortlink() as a WP-Bit LY Plug after deactivating everything works great . now Authentication would be nice :-) Greets to creative russia

    • Thanks! wp_get_shortlink is a WordPress built-in function since 3.0 I guess so yeah, you should use only one URL shortener ;) I did wrap it up in a plugin by the way, available in the directory.

    • That's nice, but although all you have to do to authenticate is attach an API key to the requests, right? But that's not about analytics, not at all. shortened links are public to everybody, and their analytics as well. A good thing would be to write a link somewhere in the admin panel that would lead to the analytics page on ;)

      Cheers, and great work!

    • You are right, but by using the authentication I can see all URL shortened under my account at once place, I don't have to keep track of all the shortened urls.

      Thanks for looking at it, really appreciated.

    • I've updated the post and the plugin to include analytics in a simple way I was thinking of, don't wanna make it too complicated 'cause I use it myself ;)

      Anyways, you keep up the great work on your side and it would be great if you implement analytics directly inside the WordPress dashboard. Cheers!

  4. WordPress Shortlink über im Artikel anzeigen | kulturbanause blog

  5. WordPress Shortlink über im Artikel anzeigen | kulturbanause blog - Artikel, Tutorials, Downloads, Tipps, Hacks, Snippets und aktuelle Szene-News rund um Webdesign und digitale Bildbearbeitung

  6. Hi Konstantin!
    I'm very thankful for the tutorial and I have already implemented it on my site. Besides using your code, I've modified Wordtwit plugin to tweet the URL Shortened by Google.
    Everything runs smoothly as expected.

    Anyway I was wondering about what Hameedullah suggested about the Google authentication so we can see all links grouped under our Google Account. If you have some time, please develop this feature.

    Thanks again.


    • Eugene, thanks for your support ;) Yeah I got a couple of such requests and yeah, I'm considering authentication as an update to the next release. Cheers!

    • Daniel, perhaps you have quite a lot of posts which means has to query the API many times in a row. Give it a few minutes then refresh the page, you should see them updated :)

Comments are closed.