I'd like to make a WordPress website self-contained. That is, all its internal resources (images, pages, etc.) should be cross-linked independently of the site location.
If I decide to move the website later (e.g. change the domain name), I should be able to do it without any changes to the content. This is a very basic requirement, and is not dissimilar to a piece of software that can be relocated to any directory without changes. Any good software allows that.
Furthermore, the website may be accessible from multiple domains simultaneously (say, foo.com
and foo.org
) on the same host, and when accessed from one, all its internal resources must be polled from the same domain it was accessed from without redirection.
An obvious way to achieve this is to use relative URLs for all internal resources, much like a good program would use relative paths to open its own internal files - or, alternatively, would construct full paths using its current location on the fly.
However, I don't see a good way to do it in WordPress. (I must say I'm new to it). It has a setting (Site Address (URL)
) which sets the root address and which is used to construct all links - and which, to my mind, shouldn't even exist: I don't know the site address yet, an it is subject to change at any moment.
This creates even more problems during development. Of course, I develop locally, on localhost
. All published (or any, really) links then refer explicitly to localhost, e.g.
<img src="http://localhost/wordpress/wp-content/uploads/foo.jpg">
But sometimes I access this computer from another (within LAN) using its real hostname and, obviously, nothing works.
This all could be solved if WordPress could generate links like src="/wp-content/uploads/foo.jpg">
instead, but I don't see how. I'm puzzled how WP makes basic things so difficult.
Maybe there is another way, like writing a function that would replace all URLs on the fly. I'm a bit lost...
EDIT
The closest question (almost a duplicate) I found is this 10-year-old one: root-relative links for multiple parked domains. I haven't tried the presented solution yet. It appears that it's relatively hard to work around, because WP was foolishly designed with absolute URLs in mind throughout...
return preg_replace('/^(.*?)\/\/(.*)\//', '/', $url);
You're going to have an issue with caching. I don't know how to force it to store URLs as relative URLs, which IMO it should by default.wp_get_attachment_url
). This works when adding new images to the page: now WP generates a correct link. But I can't figure out how to change links of the items that were added before (without replacing them anew). It seems that WP just dumbly 'bakes' the links in when they are added, and the way to change them is to do text replacement on the whole page (using some migratory tool perhaps...)