André Amorim

Crafting Web Experiences


//

Allow multiple domains to open same multisite with single database in WordPress

In some cases, you might need to clone a multisite for testing or staging purposes, but you might want to use the same database on both clone and production websites. This can be needed not to deal with data synchronization between staging and production sites when it’s ready to take the changes live. It’s especially very complicated after WordPress started using block-based posts, pages, templates.

When it comes to multisite installation of WordPress, it’s much more challenging even if you use plugins like Domain Mapping System. I’ve prepared a bunch of required WordPress hooks to allow alternative domains for main site of a multisite installation. These snippets need to be placed in the production site to allow an alternative domain. Here are the hooks that you need to add into your functions.php file:


$alternative_domain_to_allow = $_ENV['ALTERNATIVE_DOMAIN'];
$actual_domain = $_ENV['DOMAIN'];



add_filter(
    'get_site',
    function ($_site) use ($actual_domain) {
        $_site->domain = $actual_domain;
        return $_site;
    },
    10,
    1
);


add_filter(
    'pre_get_site_by_path',
    function ($site) {
        return get_site(1);
    },
    10,
    1
);


add_filter(
    'home_url',
    function ($url) use ($alternative_domain_to_allow, $actual_domain) {
        return str_replace($alternative_domain_to_allow, $actual_domain, $url);
    },
    10,
    1
);


add_filter(
    'site_url',
    function ($url) use ($alternative_domain_to_allow, $actual_domain) {
        return str_replace($alternative_domain_to_allow, $actual_domain, $url);
    },
    10,
    1
);


add_filter(
    'the_content',
    function ($content) use ($alternative_domain_to_allow, $actual_domain) {
        return str_replace($alternative_domain_to_allow, $actual_domain, $content);
    },
    10,
    1
);


add_filter(
    'nav_menu_link_attributes',
    function ($atts) use ($alternative_domain_to_allow, $actual_domain) {
        $original_href = $atts['href'];
        $atts['href'] = str_replace($alternative_domain_to_allow, $actual_domain, $original_href);

        return $atts;
    },
    10,
    1
);

Published date:

Modified date: