url.php
65 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Elementor\Core\Utils\ImportExport; |
| 4 | |
| 5 | if ( ! defined( 'ABSPATH' ) ) { |
| 6 | exit; // Exit if accessed directly |
| 7 | } |
| 8 | |
| 9 | class Url { |
| 10 | |
| 11 | /** |
| 12 | * Migrate url to the current permalink structure. |
| 13 | * The function will also check and change absolute url to relative one by the base url. |
| 14 | * This is currently supports only "Post Name" permalink structure to any permalink structure. |
| 15 | * |
| 16 | * @param string $url The url that should be migrated. |
| 17 | * @param string|Null $base_url The base url that should be clean from the url. |
| 18 | * @return string The migrated url || the $url if it couldn't find a match in the current permalink structure. |
| 19 | */ |
| 20 | public static function migrate( $url, $base_url = '' ) { |
| 21 | $full_url = $url; |
| 22 | |
| 23 | if ( ! empty( $base_url ) ) { |
| 24 | $base_url = preg_quote( $base_url, '/' ); |
| 25 | $url = preg_replace( "/^{$base_url}/", '', $url ); |
| 26 | } |
| 27 | |
| 28 | $parsed_url = wp_parse_url( $url ); |
| 29 | |
| 30 | if ( $url === $full_url && ! empty( $parsed_url['host'] ) ) { |
| 31 | return $full_url; |
| 32 | } |
| 33 | |
| 34 | if ( ! empty( $parsed_url['path'] ) ) { |
| 35 | $page = get_page_by_path( $parsed_url['path'] ); |
| 36 | |
| 37 | if ( ! $page ) { |
| 38 | return $full_url; |
| 39 | } |
| 40 | |
| 41 | $permalink = get_permalink( $page->ID ); |
| 42 | } |
| 43 | |
| 44 | if ( empty( $permalink ) ) { |
| 45 | return $full_url; |
| 46 | } |
| 47 | |
| 48 | if ( ! empty( $parsed_url['query'] ) ) { |
| 49 | parse_str( $parsed_url['query'], $parsed_query ); |
| 50 | |
| 51 | // Clean WP permalinks query args to prevent collision with the new permalink. |
| 52 | unset( $parsed_query['p'] ); |
| 53 | unset( $parsed_query['page_id'] ); |
| 54 | |
| 55 | $permalink = add_query_arg( $parsed_query, $permalink ); |
| 56 | } |
| 57 | |
| 58 | if ( ! empty( $parsed_url['fragment'] ) ) { |
| 59 | $permalink .= '#' . $parsed_url['fragment']; |
| 60 | } |
| 61 | |
| 62 | return wp_make_link_relative( $permalink ); |
| 63 | } |
| 64 | } |
| 65 |