WP_Network::get_main_site_id(): int

In this article

This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.

Returns the main site ID for the network.

Description

Internal method used by the magic getter for the ‘blog_id’ and ‘site_id’ properties.

Return

int The ID of the main site.

Source

private function get_main_site_id() {
	/**
	 * Filters the main site ID.
	 *
	 * Returning a positive integer will effectively short-circuit the function.
	 *
	 * @since 4.9.0
	 *
	 * @param int|null   $main_site_id If a positive integer is returned, it is interpreted as the main site ID.
	 * @param WP_Network $network      The network object for which the main site was detected.
	 */
	$main_site_id = (int) apply_filters( 'pre_get_main_site_id', null, $this );

	if ( 0 < $main_site_id ) {
		return $main_site_id;
	}

	if ( 0 < (int) $this->blog_id ) {
		return (int) $this->blog_id;
	}

	if ( ( defined( 'DOMAIN_CURRENT_SITE' ) && defined( 'PATH_CURRENT_SITE' )
		&& DOMAIN_CURRENT_SITE === $this->domain && PATH_CURRENT_SITE === $this->path )
		|| ( defined( 'SITE_ID_CURRENT_SITE' ) && (int) SITE_ID_CURRENT_SITE === $this->id )
	) {
		if ( defined( 'BLOG_ID_CURRENT_SITE' ) ) {
			$this->blog_id = (string) BLOG_ID_CURRENT_SITE;

			return (int) $this->blog_id;
		}

		if ( defined( 'BLOGID_CURRENT_SITE' ) ) { // Deprecated.
			$this->blog_id = (string) BLOGID_CURRENT_SITE;

			return (int) $this->blog_id;
		}
	}

	$site = get_site();
	if ( $site->domain === $this->domain && $site->path === $this->path ) {
		$main_site_id = (int) $site->id;
	} else {

		$main_site_id = get_network_option( $this->id, 'main_site' );
		if ( false === $main_site_id ) {
			$_sites       = get_sites(
				array(
					'fields'     => 'ids',
					'number'     => 1,
					'domain'     => $this->domain,
					'path'       => $this->path,
					'network_id' => $this->id,
				)
			);
			$main_site_id = ! empty( $_sites ) ? array_shift( $_sites ) : 0;

			update_network_option( $this->id, 'main_site', $main_site_id );
		}
	}

	$this->blog_id = (string) $main_site_id;

	return (int) $this->blog_id;
}

Hooks

apply_filters( ‘pre_get_main_site_id’, int|null $main_site_id, WP_Network $network )

Filters the main site ID.

Changelog

VersionDescription
4.9.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.