WordPress has a built-in function for removing protocol and domain from absolute URLs, wp_make_link_relative
, located in /wp-includes/formatting.php
:
function wp_make_link_relative( $link ) {
return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
}
To apply this function to (e.g.) permalinks, simply add a filter, as such:
add_filter( 'the_permalink', 'wp_make_link_relative' );
Deluxe Blog Tips shows how to apply this to various types of links, while making sure feed and sitemap links aren't affected:
add_action( 'template_redirect', 'rw_relative_urls' );
function rw_relative_urls() {
// Don't do anything if:
// - In feed
// - In sitemap by WordPress SEO plugin
if ( is_feed() || get_query_var( 'sitemap' ) )
return;
$filters = array(
'post_link',
'post_type_link',
'page_link',
'attachment_link',
'get_shortlink',
'post_type_archive_link',
'get_pagenum_link',
'get_comments_pagenum_link',
'term_link',
'search_link',
'day_link',
'month_link',
'year_link',
);
foreach ( $filters as $filter )
{
add_filter( $filter, 'wp_make_link_relative' );
}
}