函数文档

wp_count_sites()

💡 云策文档标注

概述

wp_count_sites() 函数用于统计 WordPress 多站点网络中按站点状态分组的站点数量。它接受一个可选的网络 ID 参数,返回包含不同状态站点计数的数组。

关键要点

  • 函数 wp_count_sites() 统计站点数量,按状态分组,包括 all、public、archived、mature、spam 和 deleted。
  • 参数 $network_id 可选,默认为当前网络 ID,用于指定要统计的网络。
  • 返回值是一个整数数组,键为状态名称,值为对应状态的站点数量。
  • 内部使用 WP_Site_Query 进行查询,通过设置查询参数来获取不同状态的站点计数。
  • 该函数自 WordPress 5.3.0 版本引入。

代码示例

function wp_count_sites( $network_id = null ) {
    if ( empty( $network_id ) ) {
        $network_id = get_current_network_id();
    }

    $counts = array();
    $args   = array(
        'network_id'    => $network_id,
        'number'        => 1,
        'fields'        => 'ids',
        'no_found_rows' => false,
    );

    $q             = new WP_Site_Query( $args );
    $counts['all'] = $q->found_sites;

    $_args    = $args;
    $statuses = array( 'public', 'archived', 'mature', 'spam', 'deleted' );

    foreach ( $statuses as $status ) {
        $_args            = $args;
        $_args[ $status ] = 1;

        $q                 = new WP_Site_Query( $_args );
        $counts[ $status ] = $q->found_sites;
    }

    return $counts;
}

📄 原文内容

Counts number of sites grouped by site status.

Parameters

$network_idintoptional
The network to get counts for. Default is the current network ID.

Default:null

Return

int[] Numbers of sites grouped by site status.

  • all int
    The total number of sites.
  • public int
    The number of public sites.
  • archived int
    The number of archived sites.
  • mature int
    The number of mature sites.
  • spam int
    The number of spam sites.
  • deleted int
    The number of deleted sites.

Source

function wp_count_sites( $network_id = null ) {
	if ( empty( $network_id ) ) {
		$network_id = get_current_network_id();
	}

	$counts = array();
	$args   = array(
		'network_id'    => $network_id,
		'number'        => 1,
		'fields'        => 'ids',
		'no_found_rows' => false,
	);

	$q             = new WP_Site_Query( $args );
	$counts['all'] = $q->found_sites;

	$_args    = $args;
	$statuses = array( 'public', 'archived', 'mature', 'spam', 'deleted' );

	foreach ( $statuses as $status ) {
		$_args            = $args;
		$_args[ $status ] = 1;

		$q                 = new WP_Site_Query( $_args );
		$counts[ $status ] = $q->found_sites;
	}

	return $counts;
}

Changelog

Version Description
5.3.0 Introduced.