get_id_from_blogname()
云策文档标注
概述
get_id_from_blogname() 函数用于根据站点的子域名或目录 slug 检索其 ID。它通过处理网络配置(子域名或目录安装)来构建查询参数,并返回站点 ID 或 null。
关键要点
- 参数:$slug(字符串,必需),表示站点的 slug。
- 返回值:int|null,成功时返回站点 ID,未找到站点时返回 null。
- 依赖函数:get_network()、is_subdomain_install()、get_sites() 用于网络和站点查询。
- 应用场景:常用于避免 slug 冲突、获取博客详情或切换博客上下文。
代码示例
// 获取站点 ID
$slug = 'first-site';
$id = get_id_from_blogname( $slug );
// 切换博客
$slug = 'another-site';
$id = get_id_from_blogname( $slug );
switch_to_blog( $id );
// 执行操作
restore_current_blog();注意事项
- 函数在 WordPress 4.7.0 版本引入,适用于多站点网络。
- slug 会自动去除首尾斜杠,确保与网络路径正确匹配。
- 查询时设置 update_site_meta_cache 为 false 以提高性能。
原文内容
Retrieves a site’s ID given its (subdomain or directory) slug.
Parameters
$slugstringrequired-
A site’s slug.
Source
function get_id_from_blogname( $slug ) {
$current_network = get_network();
$slug = trim( $slug, '/' );
if ( is_subdomain_install() ) {
$domain = $slug . '.' . preg_replace( '|^www.|', '', $current_network->domain );
$path = $current_network->path;
} else {
$domain = $current_network->domain;
$path = $current_network->path . $slug . '/';
}
$site_ids = get_sites(
array(
'number' => 1,
'fields' => 'ids',
'domain' => $domain,
'path' => $path,
'update_site_meta_cache' => false,
)
);
if ( empty( $site_ids ) ) {
return null;
}
return array_shift( $site_ids );
}
Changelog
| Version | Description |
|---|---|
| MU (3.0.0) | MU (3.0.0) |
| 4.7.0 | Introduced. |
Skip to note 2 content
Codex
Getting id of a blog by name ($slug)
$slug = 'first-site'; $id = get_id_from_blogname( $slug );Switching blogs based on the blogs name ($slug)
$slug = 'another-site'; $id = get_id_from_blogname( $slug ); switch_to_blog( $id ); // Do great things. restore_current_blog();