WordPress development team refused to change internal URLs to relative URLs with few supported argument.
- Relative URLs might incompatible with current plugins.
- Relative URLs will increase the use of processing, as well as introduce potential bugs.
- absolute URLs are needed for email and maybe RSS and RPC.
URLs delivered to the browser should be root-relative
However, I use relative URLs because of:
- domain changed benefit with relative URLs. If we need to change the domain name of the website, absolute URLs will still linking to the old domain name. The longer the website you host, the heavier the URLs you need to fix.
- If you want to make your website have multiple language provided linked as “yourwebsite.com/en/post” & “yourwebsite.com/fr/post”, relative link will provide better linking to other post without changing the URLs. E.g. you have a post had linking to another post “abc”, you can just use “./abc” as URL. Browser will process the URL as “yourwebsite.com/en/abc”. You can just use the same post as your template for translate to other languages.
Change from absolute URLs to relative URLs
Change to relative URLs with editing theme
Just add the following code in your function.php (Dashboard > Appearance > Theme editor > function.php). It will convert most of the URLs to relative URLs except sitemap and URLs in feed. To exclude the links in specific type, just delete it in the filters array.
/**
* Apply relative link
* https://developer.wordpress.org/reference/functions/wp_make_link_relative/
* */
function relative_redirect() {
// exclude if is in feed or is in sitemap
if ( is_feed() || get_query_var( 'sitemap' ) )
return;
$filters = array(
'attachment_link',
'day_link',
'get_comments_pagenum_link',
'get_pagenum_link',
'get_shortlink',
'month_link',
'page_link',
'post_link',
'post_type_archive_link',
'post_type_link',
'search_link',
'term_link',
'year_link',
);
foreach ( $filters as $filter )
{
add_filter( $filter, 'wp_make_link_relative' );
}
}
add_action( 'template_redirect', 'relative_redirect' );
I also tested the code in Relative URLs in WordPress – Stack overflow, try if the above code is not work. Remember to change the correct website URL in the code below.
/**
* Change current link to relative link
*/
add_action("template_redirect", "start_buffer");
add_action("shutdown", "end_buffer", 999);
function filter_buffer($buffer) {
$buffer = replace_insecure_links($buffer);
return $buffer;
}
function start_buffer(){
ob_start("filter_buffer");
}
function end_buffer(){
if (ob_get_length()) ob_end_flush();
}
function replace_insecure_links($str) {
$str = str_replace ( array("http://yourwebsite.com/", "https://yourwebsite.com/") , array("/", "/"), $str);
return apply_filters("rsssl_fixer_output", $str);
}
Change to relative URLs with plugin
If you don’t want to edit the theme, you can try Relative URLs and Root Relative URLs, but both plugin didn’t updated and tested in a period of times.