Hack: Use Your Post ID Numbers As Shortlinks

I hate using someone else’s URL shortener. Partially because it hides your domain name in the link and there is no reason anyone should trust it. But also because sometimes URL shortening services do bad things, like redirect product links to competing stores. Yep. I’ve experienced it.

You probably already know that you can use ?p=586 as a short link to a page or post. Just get the ID number of that item in your WordPress admin by looking at the URL when you go to edit it. But ?p=586 is ugly. What about just 586? As in this post can be accessed with https://wptipsandhacks.com/586. That’s a nice short link.

One way to do this is to use a bit of code in functions.php. This adds the rewrite rule.

add_action('init', 'wpaction_rewrite_rules');
function wpaction_rewrite_rules() {
    add_rewrite_rule('^([0-9]+)$', 'index.php?p=$matches[1]', 'top');
}

(Don’t forget you need to go to Settings, Permalink Settings and click the Save Changes button for this to work.)

This will work fine for most. But I don’t like it because the URL in the address bar will remain shortened. However, if you add the rewrite rule directly to .htaccess, then you can use the R flag and the shortened URL gets changed to ?=586 which then gets changed to the real WordPress permalink for the post. Try it: https://wptipsandhacks.com/586.

RewriteEngine On
RewriteRule ^([0-9]+)$ index.php?p=$1 [R,L]

So up to you. If you feel comfortable changing .htaccess, I like the direct approach better.

Thanks to Ask Leo for the idea!

Leave a Reply

Your email address will not be published. Required fields are marked *