Quick Tip: Add Shortlinks to Custom Post Types


This Cyber Monday Envato Tuts+ courses will be reduced to just $3. Don't miss out.

If you use any form of social media, and in particular Twitter, then you have almost certainly come across 'shortlinks' – shortened URLs which act as a label, pointing to a particular page but disguising its lengthier URL. They've been around for over a decade now, but their use really took off with URL shortening services which provided click-through statistics, and character limits on tweets.

WordPress has its own built in 'shortlink' – which, by default, probably isn't very deserving of the name. These are the links which point to a single post and you can grab them from the 'Get Shortlink' button on your post's edit screen.

There's a good reason for this: WordPress did not want to impose any particular third-party service for URL-shortening, and beneath the default shortlinks lies an API which allows you to replace it with a more substantially shortened URL from another service – or perhaps even your own.

But WordPress' shortlinks only appear on posts – not pages, or any other post type. In this quick tip I'll be showing you how to rectify this. (And in a similar way you can change the default shortlink entirely by one from a URL shortener service).

Cracking open the source code and locating the wp_get_shortlink() function (see Codex) we find the following:

The hook pre_get_shortlink, therefore, allows us to by-pass WordPress' default handling of shortlinks. To do that our plug-in needs only to hook onto that filter and return anything other than 'false'.

Note that if you do not want to change the shortlink (for instance, it's the wrong post type) it's important to return $shortlink (the filtered value that was passed to us by the hook) and not 'false' - since other plug-ins may have already changed $shortlink - and by returning false you would be overriding them.