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:

<?php

// Allow Multiple Sites with Same DB

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

// Make sure the main site is still the main site, 
// after the clone one connected and modified the domain sections of the DB
add_filter(
    'get_site',
    function ($_site) use ($actual_domain) {
        $_site->domain = $actual_domain;
        return $_site;
    },
    10,
    1
);

// This can help WP to still get main site information
add_filter(
    'pre_get_site_by_path',
    function ($site) {
        return get_site(1);
    },
    10,
    1
);

// Make sure the home URL is not changing even the clone site modifies it on DB in some way
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
);

// Make sure the site URL is not changing even the clone site modifies it on DB in some way
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
);

// Make sure there's no alternative site URL in the content of the production site
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
);

// Make sure there's no alternative site URL in the menus
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
);
Code language: PHP (php)

Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.