One of the oddest remnants of the early versions of WordPress are attachment pages. I can count on one finger the number of times I’ve thought “I’d like a dedicated page for every image on my site”. Normally, unused and illogical features like this can just be ignored. However, attachment pages aren’t just a harmless remnant of a bygone era.
Attachment pages have dedicated urls, that are based on the name of the image, and overlap with the slugs you can set for posts, pages, and custom post types. Because of this, if you upload an image named faq.jpg, you may find yourself unable to add a page at the address /faq. This can negatively impact your SEO, and is an incredibly frustrating issue to try to identify and explain to clients. Beyond the URL issue, they are another template that needs to be fully themed and branded, just in case a client runs across the page by accident. As such, they need to die.
All other post types are easy to deal with, with filters and functions to control their use of URLs. Attachments stand alone with an overly-complicated and immutable permalink structure, and no simple filters attached.
There are many snippets and instructions online detailing how to remove these pages, but most (if not all) of them simply patch over the issue with a 301 redirect or a forced 404 page. Unfortunately, those authors don’t solve the root issue of reserved slugs.
So, in that light, I wrote the definitive solution to fully disable attachment pages.
Running the plugin provided below will:
- remove all rewrite rules for attachments
- prevent attachments from reserving url paths
- prefix all slugs for new attachments, in case the plugin is ever deactivated, to minimize potential name conflicts
- rewrite all references to attachment pages urls to point to the url of the file itself
- as a final fallback, in case some sort of custom code requests an attachment page via code, that page will redirect to the attachment file.
To install the plugin, simply copy the following code to a new folder in your plugins.php directory. If there is enough interest in the comments, I will deploy the code as a plugin on the WordPress.org plugin repository, to make it simpler to install.