Is there a way to define wp_blogs domains in wp-config?

When WordPress loads multisite, it includes the relevant MS specific files in wp-settings.php

The relevant lines:

<?php
// Initialize multisite if enabled.
if ( is_multisite() ) {
    require( ABSPATH . WPINC . '/ms-blogs.php' );
    require( ABSPATH . WPINC . '/ms-settings.php' );
} elseif ( ! defined( 'MULTISITE' ) ) {
    define( 'MULTISITE', false );
}

ms-settings.php serves a similar purpose as wp-settings.php: loads the multisite environment, and — more importantly for our purposes — sets up the current site (collection of blogs) and blog. But there’s also these few gems:

if ( defined( 'SUNRISE' ) )
    include_once( WP_CONTENT_DIR . '/sunrise.php' );

/** Check for and define SUBDOMAIN_INSTALL and the deprecated VHOST constant. */
ms_subdomain_constants();

if ( !isset( $current_site ) || !isset( $current_blog ) ) {
    // setup current site and blog
}

Most important: if(defined('SUNRISE')). This lets you drop a sunrise.php file in your wp-content directory. It gets included if you define('SUNRISE', true); in your wp-config.php. This file is the same one that’s used for domain mapping to setup the current site and blog based on the custom domains. You can use it to set up your own site and blog rather than let WordPress do it for you.

Quick example — this works okay, but probably needs some improvement.

<?php
// sunrise.php

$host = $_SERVER['HTTP_HOST'];

if('wpmscustom.dev' == $host)
{
    // switch the host.
    $host="wpms.dev";
}

if(is_subdomain_install())
{
    $sql = $wpdb->prepare("SELECT * FROM {$wpdb->blogs} WHERE domain = %s LIMIT 1", $host);
}
else
{
    // this probably needs some work.
    $path = explode("https://wordpress.stackexchange.com/", ltrim($_SERVER['REQUEST_URI'], "https://wordpress.stackexchange.com/"));
    if(count($path))
        $path="https://wordpress.stackexchange.com/" . $path[0];
    else
        $path="https://wordpress.stackexchange.com/";

    $sql = $wpdb->prepare("SELECT * FROM {$wpdb->blogs} WHERE domain = %s AND path = %s LIMIT 1", $host, $path);
}

if($_blog = $wpdb->get_row($sql))
{
    $current_blog = $_blog;

    $blog_id = $_blog->blog_id;
    $site_id = $current_blog->site_id;

    // set current site
    $current_site = $wpdb->get_row(
        $wpdb->prepare("SELECT * from {$wpdb->site} WHERE id = %d", $site_id)
    );
    $current_site->blog_id = $blog_id;

    $current_site = get_current_site_name($current_site);
}

Since @kaiser will likely chime in to say that $_SERVER['HTTP_HOST'] is unreliable, you may want to make sure your server actually has it available.

Or do something like this…

<?php
if(isset( $_SERVER['HTTP_HOST']))
{
    $host = $_SERVER['HTTP_HOST'];
}
elseif(isset($_SERVER['SERVER_NAME']))
{
    $host = $_SERVER['SERVER_NAME'];
}

You can drop the above sunrise.php into your local install and put define('SUNRISE', true); into your local’s wp-config.

Leave a Comment