One Weird WordPress Trick

For quite a while, I’ve been idly wondering whether there was a simple way to use some sort of shortlink setup for WordPress media (i.e., images, videos and the like).

Here’s a typical WordPress image URL:

https://lars.ingebrigtsen.no/wp-content/uploads/2024/06/wp-17173544827964542901639383970090.jpg

I know, it’s SO LONG. But I mean, it’s an URL, so who cares… But if you’re slinging these around a lot on IRC and the like, they’re just kind of yucky, right?

So there’s a huge number of plugins for this sort of thing, but they’re mostly geared towards SEO scum, so it’s all about getting reports and tracking people and other nastinesses. (That’s a word.)

There’s also a large number of people out there that describe how to make a half-assed URL shortener yourself. This one, for instance, would create a redirect scheme that looks like:

https://lars.ingebrigtsen.no/media/wp-17173544827964542901639383970090.jpg

Which is nicer, but there’s a reason for that longer URL — you can have several images called foo.jpg from different dates, but this scheme wouldn’t allow for that.

Half an hour ago, it occurred to me that all media already has a pretty short, and also unique, way to be referred to: The attachment_id. So I thought I’d write a WordPress plugin that would allow URLs like:

https://lars.ingebrigtsen.no/media/105433

But just before I was going to start to type (I had opened the PHP file and all), I thought… “Hang on. Doesn’t WordPress have a built-in way to refer to posts and attachments by ID? I’ve seen that somewhere!”

So I just tried:

https://lars.ingebrigtsen.no/?p=105433

And it works! All these shorteners and self-rolled solutions are totally unnecessary!

So this is a Public Service Announcement for People Who Google How To Use A Shortlink (i.e., URL Shortener) For WordPress Media (you think that’s enough keywords for Google to pick this up? Probably not):

You don’t need a plugin. Just use the built-in ?p= for media, too.

Oh, and if your WordPress client doesn’t expose these IDs directly, you can find them in the web interface:

It’s down there in the “Edit more details” link.

You’re welcome.

Leave a Reply