| 448 | | } elseif ( is_attachment() |
| 449 | | && ! array_diff( array_keys( $wp->query_vars ), array( 'attachment', 'attachment_id' ) ) |
| 450 | | && ! $redirect_url |
| 451 | | ) { |
| 452 | | $redirect_url = get_attachment_link( get_query_var( 'attachment_id' ) ); |
| 453 | | $redirect_obj = get_post( get_query_var( 'attachment_id' ) ); |
| | 448 | } elseif ( is_attachment() |
| | 449 | && ! array_diff( array_keys( $wp->query_vars ), array( 'attachment', 'attachment_id' ) ) |
| | 450 | && ! $redirect_url |
| | 451 | ) { |
| | 452 | |
| | 453 | // Existing WordPress canonical behavior. |
| | 454 | $redirect_url = get_attachment_link( get_query_var( 'attachment_id' ) ); |
| | 455 | $redirect_obj = get_post( get_query_var( 'attachment_id' ) ); |
| | 456 | |
| | 457 | /** |
| | 458 | * NEW: Redirect old media URLs to the new plain-name permalink structure. |
| | 459 | * |
| | 460 | * OLD: |
| | 461 | * /?attachment_id=123 |
| | 462 | * /uploads/2023/10/photo.jpg |
| | 463 | * |
| | 464 | * NEW: |
| | 465 | * /photo/ |
| | 466 | */ |
| | 467 | if ( $redirect_obj && 'attachment' === $redirect_obj->post_type ) { |
| | 468 | |
| | 469 | // Build clean permalink based on post_name. |
| | 470 | $new_structure_url = home_url( '/' . $redirect_obj->post_name . '/' ); |
| | 471 | |
| | 472 | // Apply redirect only if URL differs from current permalink. |
| | 473 | if ( $new_structure_url !== $redirect_url ) { |
| | 474 | $redirect_url = $new_structure_url; |
| | 475 | } |
| | 476 | } |
| | 477 | |
| | 478 | if ( $redirect_url ) { |
| | 479 | $redirect['query'] = remove_query_arg( 'attachment_id', $redirect['query'] ); |
| | 480 | } |