diff --git a/src/wp-includes/canonical.php b/src/wp-includes/canonical.php index 184fb756e8..0defa8227d 100644 --- a/src/wp-includes/canonical.php +++ b/src/wp-includes/canonical.php @@ -847,11 +847,17 @@ function _remove_qs_args_if_not_in_url( $query_string, array $args_to_check, $ur * @return string The altered URL. */ function strip_fragment_from_url( $url ) { - $parsed_url = parse_url( $url ); + $parsed_url = wp_parse_url( $url ); if ( ! empty( $parsed_url['host'] ) ) { - // This mirrors code in redirect_canonical(). It does not handle every case. - $url = $parsed_url['scheme'] . '://' . $parsed_url['host']; + $url = ''; + + if ( ! empty( $parsed_url['scheme'] ) ) { + $url = $parsed_url['scheme'] . ':'; + } + + $url .= '//' . $parsed_url['host']; + if ( ! empty( $parsed_url['port'] ) ) { $url .= ':' . $parsed_url['port']; } diff --git a/tests/phpunit/tests/canonical/stripFragmentFromUrl.php b/tests/phpunit/tests/canonical/stripFragmentFromUrl.php new file mode 100644 index 0000000000..053ad88528 --- /dev/null +++ b/tests/phpunit/tests/canonical/stripFragmentFromUrl.php @@ -0,0 +1,40 @@ +assertSame( $expected, strip_fragment_from_url( $test_url ) ); + } + + /** + * Data provider for test_strip_fragment_from_url(). + * + * @return array[] { + * Data to test with. + * + * @type string $0 The test URL. + * @type string $1 The expected canonical URL. + * } + */ + public function data_strip_fragment_from_url() { + return array( + array( '//example.com', '//example.com' ), + array( 'http://example.com', 'http://example.com' ), + array( 'https://example.com', 'https://example.com' ), + array( 'https://example.com/', 'https://example.com/' ), + array( 'https://example.com/?test', 'https://example.com/?test' ), + array( 'https://example.com/?#test', 'https://example.com/' ), + array( 'https://example.com/?#test#', 'https://example.com/' ), + ); + } +}