WordPress use Relative URLs

WordPress likes to add full URLs to CMS content. This is a problem.

  • Should you change your domain name, the old domain will be shown in every single hyperlink
  • Should you want to manipulate links based on the URL, you can’t use http as a hook for external links.
  • Internal links that start with a slash are cleaner and easier to read
  • The full URL isn’t needed to make the site work

Function to use Relative URLs

Add this function to your functions.php file. It will tell WordPress to use relative links between pages and images.

function switch_to_relative_url($html, $id, $caption, $title, $align, $url, $size, $alt)
{
$imageurl = wp_get_attachment_image_src($id, $size);
$relativeurl = wp_make_link_relative($imageurl[0]);   
$html = str_replace($imageurl[0],$relativeurl,$html);    
return $html;
}
add_filter('image_send_to_editor','switch_to_relative_url',10,8);