Make WordPress Core

Ticket #64376: 64376.diff

File 64376.diff, 1.7 KB (added by iflairwebtechnologies, 2 months ago)

canonical: avoid unnecessary redirects for encoding-only differences (fix #64376)

  • wp-includes/canonical.php

    diff --git a/wp-includes/canonical.php b/wp-includes/canonical.php
    index 8b13789..8f52abc 100644
    a b function redirect_canonical( $requested_url = null, $do_redirect = true ) { 
    445445                $redirect['path'] = $redirect_obj->path;
    446446
    447447        // Attachment (non-empty attachment_id, no attachment slug, & no other query vars).
    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                }
    454481        }
    455482