site_url()
云策文档标注
概述
site_url() 函数用于获取当前 WordPress 站点应用文件(如 wp-blog-header.php 或 wp-admin/ 文件夹)可访问的 URL。它基于 'site_url' 选项返回,并可根据 SSL 状态或指定方案调整协议。
关键要点
- 返回站点 URL,默认根据 is_ssl() 自动选择 http 或 https 协议
- 接受可选参数 $path 用于追加相对路径,$scheme 用于指定 URL 方案(如 'http'、'https'、'admin' 等)
- 如果 $scheme 明确指定为 'http' 或 'https',将覆盖 is_ssl() 的检测结果
- 函数内部调用 get_site_url(),返回字符串类型的 URL
- 适用于需要访问 WordPress 核心文件路径的场景,与 home_url() 区分(后者返回站点首页 URL)
代码示例
$url = site_url();
echo $url;
// 输出: http://www.example.com 或 http://www.example.com/wordpress(无尾部斜杠)
$url = site_url( '/secrets/', 'https' );
echo $url;
// 输出: https://www.example.com/secrets/ 或 https://www.example.com/wordpress/secrets/注意事项
- 当 WordPress 安装在子目录(如 /wordpress/)时,URL 可能包含该目录路径
- 如需获取站点首页 URL,应使用 home_url() 而非 site_url()
- 参数 $scheme 支持多种方案,包括 'relative'、'rest'、'rpc' 等,具体参考 set_url_scheme()
原文内容
Retrieves the URL for the current site where WordPress application files (e.g. wp-blog-header.php or the wp-admin/ folder) are accessible.
Description
Returns the ‘site_url’ option with the appropriate protocol, ‘https’ if is_ssl() and ‘http’ otherwise. If $scheme is ‘http’ or ‘https’, is_ssl() is overridden.
Parameters
$pathstringoptional-
Path relative to the site URL. Default empty.
$schemestring|nulloptional-
Scheme to give the site URL context. See set_url_scheme() .
More Arguments from set_url_scheme( … $scheme )
Scheme to give $url. Currently
'http','https','login','login_post','admin','relative','rest','rpc', or null.Default:
null
Source
function site_url( $path = '', $scheme = null ) {
return get_site_url( null, $path, $scheme );
}
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |
Skip to note 3 content
Codex
Examples
$url = site_url(); echo $url;Output:
http://www.example.comorhttp://www.example.com/wordpress(Note the lack of a trailing slash)
$url = site_url( '/secrets/', 'https' ); echo $url;Output:
https://www.example.com/secrets/orhttps://www.example.com/wordpress/secrets/Skip to note 4 content
mirgcire
The contributed example is unclear because it states that the result is one of two options, but no information is given to determine which option to expect. Are we to assume it is random, and therefore must filter out the spurious occurrences of “wordpress”?