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 ;)
[…] This post was mentioned on Twitter by Konstantin Kovshenin, Konstantin Kovshenin and others. Konstantin Kovshenin said: Using #Google’s URL Shortener (goo.gl) in #WordPress http://goo.gl/fb/D9trA #snippets […]
And how i can save my email and password to see it in my google account?
Good question. See Authentication
[…] here: Using Google’s URL Shortener (goo.gl) in WordPress Tags: programming, seo, webdesign, […]
Great work kovsheni just was surprised that my first result was a bit.ly 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.
Hi, You might like the plugin I have created, using wp_get_shortlink too. My plugin also supports google authenticate so you can track clicks and other analytics of your shorted urls. http://hameedullah.com/wordpress/wpgoogl.
I would love to have your feedback. :)
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. Goo.gl 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 Goo.gl ;)
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.
Good point, but you're still keeping track of all the shortened URLs as I do by caching in post meta, right? ;)
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!
[…] Das Shortlink-Snippet stammt von Otto on WordPress; die goo.gl Umsetzung von Konstantin […]
[…] Das Shortlink-Snippet stammt von Otto on WordPress; die goo.gl Umsetzung von Konstantin […]
Many thanks, man, worked like a charm, except for the Analytics part wichg is kinda over my head.
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
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!
Hi, I have installed your plugin yesterday, and notice that the shortlinks are not always created. This is a screenshot from my posts control panel:
http://i.imgur.com/Cudh1.png
so for example this post has a shortlink:
http://www.aeromental.com/2011/07/25/si-los-naveg…
(The shortlink is published bellow the post in a grey box)
and this posts has none:
http://www.aeromental.com/2011/07/27/tatuaje-del-…
Daniel, perhaps you have quite a lot of posts which means Goo.gl has to query the API many times in a row. Give it a few minutes then refresh the page, you should see them updated :)