Roots Discourse

Convert links and images to being site root relative

I love the way Roots cleans up clutter, and in particular makes many links into being site root relative. There has been an ongoing discussion at WordPress as to whether absolute or site root relative URLs are the best way forwards, but it seems absolute always wins, which is a shame.

I find it frustrating the way links and images in the WP editor are always absolute. This means slightly more code, more clutter, more difficulty in changing domain names and problems with sites that are partly using HTTPS.

I came across a function that converts links in the WP editor to being site root relative. The conversion happens when you save or publish a post or page. Maybe some of you might find this useful. It would be cool if something like this was baked into Roots.

// Convert absolute URLs in content to site relative ones
// Inspired by
function sp_clean_static_url($content) {
   $thisURL = get_bloginfo('url');
   $stuff = str_replace(' src=\"'.$thisURL, ' src=\"', $content );
   $stuff = str_replace(' href=\"'.$thisURL, ' href=\"', $stuff );
	return $stuff;

This looks good - has this been tested with Roots URL re-writes?

If so, i may have to add this to my collection!

Roots doesn’t rewrite URLs from the editor, so this doesn’t conflict at all. I’ve used the above code in quite a few of my sites, and it works really well. Let me know how you get on.

Started doing some research on this and found the following plugin:

It hooks in when the image is being sent to the editor and my preliminary tests all passed. Here is the function from the plugin which you can paste into your own functionality function if you are interested:

function image_to_relative($html, $id, $caption, $title, $align, $url, $size, $alt) {
	$sp = strpos($html,"src=") + 5;
	$ep = strpos($html,"\"",$sp);
	$imageurl = substr($html,$sp,$ep-$sp);
	$relativeurl = str_replace("http://","",$imageurl);
	$sp = strpos($relativeurl,"/");
	$relativeurl = substr($relativeurl,$sp);
	$html = str_replace($imageurl,$relativeurl,$html);
	return $html;
add_filter('image_send_to_editor', 'image_to_relative', 5, 8);

Also, this plugin author has another plugin which changes the Image Link default to ‘None’ which is handy in my case since I rarely want the image to link anywhere.


Works well, although it misses https links. Simple enough to fix:

   function image_to_relative($html, $id, $caption, $title, $align, $url, $size, $alt)
		$sp = strpos($html, "src=") + 5;
		$ep = strpos($html, "\"", $sp);

		$imageurl = substr($html, $sp, $ep-$sp);

		$relativeurl = str_replace(["http://", "https://"], "", $imageurl);
		$sp = strpos($relativeurl, "/");
		$relativeurl = substr($relativeurl, $sp);

		$html = str_replace($imageurl, $relativeurl, $html);

		return $html;