Apr 5, 2016

Get the ID of the Main Site in a WordPress Multisite Network

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.

/*
 * 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 less than 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.

/*
 * 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;
}