Redirect attachment pages in WordPress without a plugin
Stop WordPress showing a thin page for every upload with one line of code. The Snipfire snippet sends visitors to the file; Attachment Pages Redirect sends them to the post.
What Attachment Pages Redirect does
Attachment Pages Redirect sends visitors from an image's attachment page to the post it was uploaded to, or to the home page if there isn't one. The plugin on WordPress.org
What the snippet does the same
- Visitors and search engines no longer see the thin attachment page for each upload.
- There are no settings in either.
What's different
- The snippet sends visitors to the file itself, using the setting WordPress 6.4 and later uses on new sites. The plugin sends them to the post the file was uploaded to.
- The plugin sends files that aren't attached to a post to the home page, and shows a 404 page when the post is in the bin. The snippet sends every attachment page to its file.
When to keep the plugin Keep the plugin if you would rather send visitors to the post an image belongs to than to the image file.
The snippet: Send attachment pages to the file
Each uploaded image has its own thin page (…/image-name/). This sends visitors straight to the file instead, as new WordPress sites do.
<?php
// The same setting WordPress 6.4+ uses on new sites.
add_filter( 'pre_option_wp_attachment_pages_enabled', static fn() => '0' );
Notes, where it runs and what it was tested with
Switching from the plugin
- Install the snippet in Snipfire (it arrives switched off).
- Deactivate Attachment Pages Redirect.
- Switch the snippet on. Snipfire checks the code and test-loads your site first.
- Check the page it affects, then delete the plugin.