Two (or more) parallel (sub-)TLDs that are retained when surfing the site / dynamically set the site address?

I am running a site for a German NGO under the domain sub.example.org.
Recently, I added sub.example.ch for its Swiss spin-off.

Both (sub-)domains are pointing to the same physical location, a WP install (not multisite).

I have it setup such that sub.example.ch/register, for instance, will correctly show the content found under sub.example.org/register.

However, when a Swiss visitor surfs the site using regular on-site links, he or she will inevitably end up on the “regular” domain, since those utilize the “WordPress address” (or “site address”) as defined in general settings, either via get_home_url or get_site_url() (or their less-deep get_bloginfo() equivalents).

Ideally, I’d like the visitor to keep surfing under the domain that he or she used to reach the site. Hence, I suppose I’d have to somehow filter the return value of the mentioned functions. A filter, which, as far as I know, does not exist.

  1. Does anybody have experience with this sort of thing and a decent solution handy?

  2. Is this maybe a dumb idea and I should let it go in the first place?

Solutions Collecting From Web of "Two (or more) parallel (sub-)TLDs that are retained when surfing the site / dynamically set the site address?"

You could filter the option requests for the host.

In your wp-config.php below the line …

require_once ABSPATH . 'wp-settings.php';

… add the following lines:

add_filter( 'pre_option_home', 'set_current_host' );
add_filter( 'pre_option_siteurl', 'set_current_host' );

function set_current_host()
{
    return 'http://' . $_SERVER['HTTP_HOST'];
}

add_filter() is not available earlier, and you should keep such code in your wp-config.php. I don’t know if there are side effect or cases where it doesn’t work. Should not happen, but test it thoroughly.