wp_make_link_relative()
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
#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('http://example.com/foo/?bar=baz'); //> /foo/?bar=baz echo wp_make_link_relative('/sample-page/'); //> /sample-page/ echo wp_make_link_relative('//example.com/sample-page/'); //> /sample-page/ echo wp_make_link_relative( 'http://example.com/image.jpg 1x' ); //> /image.jpg 1x echo wp_make_link_relative( '' ); //> ''
However, keep in mind:
echo wp_make_link_relative( '//wp-content/file.png' ); //> /file.png
#2 Another option is to make the absolute URL a relative one
To do this, you can use wp_parse_url() with the parameter PHP_URL_PATH
:
wp_parse_url( 'http://example.com/foo/page/', PHP_URL_PATH ); // /foo/page/
It differs in that it cuts off all query parameters beginning with ``?
wp_parse_url( 'http://example.com/foo/?bar=baz', PHP_URL_PATH ); // /foo/
Compare this to wp_make_link_relative():
$res = [ wp_make_link_relative( 'http://example.com/foo/?bar=baz' ), wp_make_link_relative( 'http://example.com/foo/page/' ), wp_make_link_relative( '/sample-page/' ), wp_make_link_relative( '//example.com/sample-page/' ), wp_make_link_relative( 'http://example.com/image.jpg 1x' ), wp_make_link_relative( '//wp-content/file.png' ), ]; $res2 = [ wp_parse_url( 'http://example.com/foo/?bar=baz', PHP_URL_PATH ), wp_parse_url( 'http://example.com/foo/page/', PHP_URL_PATH ), wp_parse_url( '/sample-page/', PHP_URL_PATH), wp_parse_url( '//example.com/sample-page/', PHP_URL_PATH), wp_parse_url( 'http://example.com/image.jpg 1x', PHP_URL_PATH ), wp_parse_url( '//wp-content/file.png', PHP_URL_PATH ), ]; foreach( $res as $k => $re ){ echo ( $re === $res2[ $k ] ? 'YES' : 'NO' ) . " - $re === {$res2[ $k ]}\n"; } /* NO - /foo/?bar=baz === /foo/ YES - /foo/page/ === /foo/page/ YES - /sample-page/ === /sample-page/ YES - /sample-page/ === /sample-page/ YES - /image.jpg 1x === /image.jpg 1x YES - /file.png === /file.png */
Changelog
Since 2.1.0 | Introduced. |
Since 4.1.0 | Support was added for relative URLs. |
wp_make_link_relative() wp make link relative code WP 6.7.1
function wp_make_link_relative( $link ) { return preg_replace( '|^(https?:)?//[^/]+(/?.*)|i', '$2', $link ); }