Skip to main content

If have you ever used wordpress in an environment where you have dev, testing, staging and production environments you would understand that the default wordpress uses when inserting media into posts is by adding the complete url to the media item. Now In a scenario where you have different environments with different urls and you use git and scripts to snc the database between the environments the full url can cause issues because as soon as its deployed to a new environment the urls will differ and your images in your content will be broken.

So the easiest way to fight this is by changing the way wordpress inserts the media items, instead of adding in the full url’s rather add them with a relative url. What this means is instead of adding a url like “” it will insert a url like “/wp-content/uploads/07/images.jpg”.

Basicly it doesnt matter what the domain is the images will include correctly and when deployed over to new environment it will work fine.

So this can be accomplished with a few lines of code that you can add into the functions.php of your theme.

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;
Janes Oosthuizen

Author Janes Oosthuizen

Programmer and Tech Junky from Cape Town, South-Africa. I have been programming for more than 15 years in various languages including ( CSS, HTML, javascript, PHP, MySQL, Wordpress and many other ).

More posts by Janes Oosthuizen

Leave a Reply