get_blog_id_from_url()
云策文档标注
概述
get_blog_id_from_url() 函数用于根据博客的 URL 获取其数字 ID,适用于 WordPress 多站点安装。它通过域名和路径参数匹配站点,并利用缓存优化性能。
关键要点
- 函数接受两个参数:$domain(必需,网站域名)和 $path(可选,默认为 '/'),用于指定博客的 URL 结构。
- 在子目录安装(如 example.com/blog1/)中,$domain 为根域名,$path 为子目录路径;在子域名安装(如 blog1.example.com)中,$domain 为完整子域名,$path 通常为 '/'。
- 返回值:如果未找到匹配博客,返回 0;否则返回博客的 ID(整数)。
- 函数内部使用 wp_cache_get() 和 wp_cache_set() 进行缓存管理,以提高查询效率。
- 通过 get_sites() 查询数据库获取博客 ID,支持参数如 'domain'、'path'、'fields' 等。
代码示例
// For subdirectory installs
$blog_id = get_blog_id_from_url( "example.com", "/blog1/" );
// For subdomain installs
$blog_id = get_blog_id_from_url( "blog1.example.com" );
原文内容
Gets a blog’s numeric ID from its URL.
Description
On a subdirectory installation like example.com/blog1/, $domain will be the root ‘example.com’ and $path the subdirectory ‘/blog1/’. With subdomains like blog1.example.com, $domain is ‘blog1.example.com’ and $path is ‘/’.
Parameters
$domainstringrequired-
Website domain.
$pathstringoptional-
Not required for subdomain installations. Default
'/'.
Source
function get_blog_id_from_url( $domain, $path = '/' ) {
$domain = strtolower( $domain );
$path = strtolower( $path );
$id = wp_cache_get( md5( $domain . $path ), 'blog-id-cache' );
if ( -1 === $id ) { // Blog does not exist.
return 0;
} elseif ( $id ) {
return (int) $id;
}
$args = array(
'domain' => $domain,
'path' => $path,
'fields' => 'ids',
'number' => 1,
'update_site_meta_cache' => false,
);
$result = get_sites( $args );
$id = array_shift( $result );
if ( ! $id ) {
wp_cache_set( md5( $domain . $path ), -1, 'blog-id-cache' );
return 0;
}
wp_cache_set( md5( $domain . $path ), $id, 'blog-id-cache' );
return $id;
}
Changelog
| Version | Description |
|---|---|
| MU (3.0.0) | Introduced. |
Skip to note 2 content
Codex
Example
// For subdirectory installs $blog_id = get_blog_id_from_url( "example.com", "/blog1/" ); // For subdomain installs $blog_id = get_blog_id_from_url( "blog1.example.com" );