diff --git a/src/wp-includes/query.php b/src/wp-includes/query.php index 592e70e0290a3..bf7af551781cf 100644 --- a/src/wp-includes/query.php +++ b/src/wp-includes/query.php @@ -1104,6 +1104,21 @@ function wp_old_slug_redirect() { $link = user_trailingslashit( trailingslashit( $link ) . 'embed' ); } + $query_string = isset( $_SERVER['QUERY_STRING'] ) ? (string) $_SERVER['QUERY_STRING'] : ''; + + if ( '' !== $query_string ) { + $fragment = strstr( $link, '#' ); + + if ( false !== $fragment ) { + $link = substr( $link, 0, -strlen( $fragment ) ); + } else { + $fragment = ''; + } + + $link .= false === strpos( $link, '?' ) ? '?' : '&'; + $link .= $query_string . $fragment; + } + /** * Filters the old slug redirect URL. * diff --git a/tests/phpunit/tests/rewrite/oldSlugRedirect.php b/tests/phpunit/tests/rewrite/oldSlugRedirect.php index cf38ba452eabf..ddbf6497d032f 100644 --- a/tests/phpunit/tests/rewrite/oldSlugRedirect.php +++ b/tests/phpunit/tests/rewrite/oldSlugRedirect.php @@ -34,6 +34,7 @@ public function set_up() { public function tear_down() { $this->old_slug_redirect_url = null; + unset( $_SERVER['QUERY_STRING'] ); parent::tear_down(); } @@ -55,6 +56,59 @@ public function test_old_slug_redirect() { $this->assertSame( $permalink, $this->old_slug_redirect_url ); } + /** + * @ticket 65267 + */ + public function test_old_slug_redirect_preserves_query_string() { + $old_permalink = user_trailingslashit( get_permalink( self::$post_id ) ); + + wp_update_post( + array( + 'ID' => self::$post_id, + 'post_name' => 'bar-baz', + ) + ); + + $permalink = user_trailingslashit( get_permalink( self::$post_id ) ); + $query_string = 'utm_source=flyer&foo=a%2Bb&a=1&a=2'; + + $this->go_to( $old_permalink . '?' . $query_string ); + $_SERVER['QUERY_STRING'] = $query_string; + + wp_old_slug_redirect(); + $this->assertSame( $permalink . '?' . $query_string, $this->old_slug_redirect_url ); + } + + /** + * @ticket 65267 + */ + public function test_old_slug_redirect_preserves_query_string_before_fragment() { + $old_permalink = user_trailingslashit( get_permalink( self::$post_id ) ); + + wp_update_post( + array( + 'ID' => self::$post_id, + 'post_name' => 'bar-baz', + ) + ); + + $permalink = user_trailingslashit( get_permalink( self::$post_id ) ) . '?existing=1'; + $query_string = 'utm_source=flyer'; + + add_filter( + 'post_link', + static function ( $url ) { + return $url . '?existing=1#campaign-details'; + } + ); + + $this->go_to( $old_permalink . '?' . $query_string ); + $_SERVER['QUERY_STRING'] = $query_string; + + wp_old_slug_redirect(); + $this->assertSame( $permalink . '&' . $query_string . '#campaign-details', $this->old_slug_redirect_url ); + } + /** * @ticket 36723 */