[wp-trac] [WordPress Trac] #65230: `redirect_canonical()` fails to redirect slug-based attachment URLs when `wp_attachment_pages_enabled` is disabled
WordPress Trac
noreply at wordpress.org
Wed May 13 04:43:14 UTC 2026
#65230: `redirect_canonical()` fails to redirect slug-based attachment URLs when
`wp_attachment_pages_enabled` is disabled
--------------------------+-----------------------------
Reporter: dd32 | Owner: (none)
Type: defect (bug) | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Media | Version:
Severity: normal | Keywords:
Focuses: |
--------------------------+-----------------------------
When attachment pages are disabled (`wp_attachment_pages_enabled = 0`) and
pretty permalinks are in use, visiting an attachment via its slug URL
(e.g. `/my-image-jpg/`) returns a 200 with the attachment page rendered,
instead of redirecting to the file. The query-string form
(`?attachment_id=123`) for the same attachment correctly redirects.
This is a follow-up to #59866, which addressed the logged-in/anonymous
discrepancy but did not cover the slug-URL code path.
**Steps to reproduce**
1. Enable pretty permalinks (e.g. `/%postname%/`).
2. Set `wp_attachment_pages_enabled` to `0`.
3. Upload any media file.
4. Visit the attachment's pretty permalink, e.g. `/my-image-jpg/`.
**Expected:** 301 redirect to the file URL (e.g. `/wp-
content/uploads/2026/05/my-image.jpg`).
**Actual:** 200 response with an attachment page rendered.
**Cause**
In `src/wp-includes/canonical.php` (~line 553), inside the
`is_attachment() && ! get_option( 'wp_attachment_pages_enabled' )` block:
{{{#!php
$attachment_id = get_query_var( 'attachment_id' );
$attachment_post = get_post( $attachment_id );
}}}
`get_query_var( 'attachment_id' )` is only populated for
`?attachment_id=ID` URLs. For slug-based URLs the query var is empty, so
`get_post( '' )` returns `null`, `$attachment_url` is falsy, and the
redirect branch silently falls through.
**Prior tickets**
- #59866 — Attachment pages are only disabled for users that are logged in
(fixed in 6.4.3; this ticket covers the slug-URL gap missed there)
- #57913 — Attachment pages need to have an "on" toggle (introduced the
option)
''Note: AI was used in the preparation of this ticket.''
--
Ticket URL: <https://core.trac.wordpress.org/ticket/65230>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list