get_current_network_id()
云策文档标注
概述
get_current_network_id() 函数用于检索当前网络的 ID,在 WordPress 多站点环境中特别有用。它返回一个整数,表示当前网络的 ID,如果未启用多站点则返回 1。
关键要点
- 函数返回当前网络的 ID,类型为整数
- 如果未启用多站点(is_multisite() 返回 false),则返回 1
- 函数内部调用 get_network() 获取网络对象,并检查 id 属性是否存在
- 如果网络对象的 id 未设置,则返回主网络 ID(通过 get_main_network_id())
- 使用 absint() 确保返回值为非负整数
- 在多站点上下文中,注意此函数返回的是 site_id,而非 blog_id,这可能与预期不符
代码示例
function get_current_network_id() {
if ( ! is_multisite() ) {
return 1;
}
$current_network = get_network();
if ( ! isset( $current_network->id ) ) {
return get_main_network_id();
}
return absint( $current_network->id );
}注意事项
- 在多站点环境中,此函数返回的是 site_id,而不是 blog_id;如果需要 blog_id,应使用 get_current_blog_id()
- 函数自 WordPress 4.6.0 版本引入
- 相关函数包括 get_network()、get_main_network_id()、is_multisite() 和 absint()
原文内容
Retrieves the current network ID.
Source
function get_current_network_id() {
if ( ! is_multisite() ) {
return 1;
}
$current_network = get_network();
if ( ! isset( $current_network->id ) ) {
return get_main_network_id();
}
return absint( $current_network->id );
}
Changelog
| Version | Description |
|---|---|
| 4.6.0 | Introduced. |
Skip to note 2 content
Preliot
Warning: This function returns the site_id and not the expected blog_id in multisite context.
I was creating a plugin and used get_current_network_id() to get the current network site. It seemed to fail, because it kept returning 1. The solution was to use get_current_blog_id() .