Here’s how you can get the ID of the main site in a WordPress multisite network. This can be useful for switching to that blog using switch_to_blog( $blog_id )
to gain access to data from that site, then switching back with restore_current_blog()
for example.
<?php | |
/* | |
* Get the Blog ID of the main site in a multisite network. | |
* | |
* @return int The blog_id of the main site. | |
*/ | |
function km_get_main_site_blog_id() { | |
return get_network()->site_id; | |
} |
Alternate function for WordPress versions < 4.6.0
For sites running a WordPress version lower than 4.6.0, the function below can be used as an alternative. Note that although the $current_site
global variable name in the code below makes it look like we’re getting the blog ID for the current site, $current_site
actually refers to the data WordPress has stored related to the main site specifically, which is what we want.
<?php | |
/* | |
* Get the ID of the main site in a multisite network | |
* | |
* @return int The blog_id of the main site | |
*/ | |
function km_get_main_site_id() { | |
global $current_site; | |
return $current_site->blog_id; | |
} |
Written by Kellen Mace, who lives in Rochester Hills, MI and builds cool stuff on the web. About Kellen // Follow him on Twitter →