What is the best way to load the WP environment in a subdomain of my multisite WordPress install?

Use the defines to make it pick the site you want it to pick.

You can define these four to setup the $current_site values properly: DOMAIN_CURRENT_SITE, PATH_CURRENT_SITE, SITE_ID_CURRENT_SITE, BLOG_ID_CURRENT_SITE.

If you check the wpmu_current_site() function in ms-load.php, you’ll see that it uses those to create the $current_site global.

You may or may not have to populate the $current_blog global manually. Not sure. Try it and see.

So realistically, all you have to do is add something like this before you call wp-load.php:

define( 'DOMAIN_CURRENT_SITE', 'example.com' );
define( 'PATH_CURRENT_SITE', "https://wordpress.stackexchange.com/" );
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 1 );

With the right values for your main example.com site, of course.

If you don’t want to put these in the sub-domain’s php files themselves, then you can do something like this in either the wp-config.php or the sunrise.php file (if you define SUNRISE to true in the wp-config.php as well, of course).

if ( $_SERVER['HTTP_HOST'] == 'sub1.example.com' || 
     $_SERVER['HTTP_HOST'] == 'sub2.example.com') {
    define( 'DOMAIN_CURRENT_SITE', 'example.com' );
    define( 'PATH_CURRENT_SITE', "https://wordpress.stackexchange.com/" );
    define( 'SITE_ID_CURRENT_SITE', 1 );
    define( 'BLOG_ID_CURRENT_SITE', 1 );
}

That’s pretty much what the sunrise file load is there for, to allow a place where you can manually override things like this. Advantage of using sunrise.php over wp-config.php for it (which also works) is that you can easily turn sunrise on and off somewhere else, for testing and debugging and such.

Leave a Comment