wp_make_link_relative()WP 2.1.0

Convert full URL paths to absolute paths.

Removes the http or https protocols and the domain. Keeps the path '/' at the beginning, so it isn't a true relative link, but from the web root base.

1 time — 0.00002 sec (very fast) | 50000 times — 0.02 sec (speed of light) | PHP 7.1.5, WP 4.8

No Hooks.

Return

String. Absolute path.

Usage

wp_make_link_relative( $link );
$link(string) (required)
Full URL path.

Examples

0

#1 Create a relative URL from an absolute one

Examples of what the function outputs when passing different URLs.

echo wp_make_link_relative('http://example.com/foo/page/'); //> /foo/page/

echo wp_make_link_relative('/sample-page/'); //> /sample-page/

echo wp_make_link_relative('//site.ru/sample-page/'); //> /sample-page/

echo wp_make_link_relative( 'http://example.com/image.jpg 1x' ); //> /image.jpg 1x

Changelog

Since 2.1.0 Introduced.
Since 4.1.0 Support was added for relative URLs.

Code of wp_make_link_relative() WP 5.9.3

function wp_make_link_relative( $link ) {
	return preg_replace( '|^(https?:)?//[^/]+(/?.*)|i', '$2', $link );
}