How to remove absolute image srcs in WordPress

I use WordPress for this site but to be honest, I absolutely hate WordPress.

Comment spam, Malware hacks, hostname is part of the config, answer to everything is a plugin, etc, etc, yuk, yuk, yuk.

I use it because all I want to do is make posts, and for that, it is fine. A lot of other people use it for Content Management on complex websites, and that’s where it starts to fall apart.

For instance, lets say you have a pretty important website, where you want changes to be verified by the site owner before they go live. So you do the sensible thing, and create a staging environment (, and promote code and DB changes to your live site ( directly from your staging site, rather than manually updating your live site.

That’s the way things are done in the grown up Internet, but if you try to do this with WordPress, you’ve entered a world of pain.

When you use WordPress’s Media Library to put an image in a post, WordPress insists on creating an absolute src attribute for the image, including the protocol and the hostname.


<img src="" src="" />

when ideally it should be using an absolute URL without the protocol and hostname


 <img src="" src="/wp-content/upload/catpic.jpg" />

This means that you can’t port your site directing from staging to live, as your live site will contain images that are being pulled from your staging site. The same problem applies if you are changing your site to a completely different domain name.

Consulting the WP forums you will find all manner of solutions to this, ranging from (yes, you’ve guessed it) plugins, to running MySQL queries every time you want to update you site.

A much simpler way to do this is to user JQuery, which you insert into your code once (in script tags in the footer of your theme), and then never worry about again.

The necessary JQuery is as follows:

jQuery('img').each(function () {
       var curSrc = jQuery(this).attr('src');
       if (curSrc.substring(0, curSrc.indexOf('/', 4)) == 'http:') {
          var baseURL = curSrc.substring(0, curSrc.indexOf('/', 14));

What this does:

Each time your page loads, JQuery will cycle through all the images on that page. If it finds an image src that includes the protocol specifier ‘http:’, it will check what the base URL of your page is, and remove that value from the src of the image.

This will leave you with a page on which all the images are loaded relative to the root of your web server, rather than a Fully Qualified Domain Name.

Leave a Reply

Your email address will not be published.