函数文档

home_url()

💡 云策文档标注

概述

home_url() 函数用于获取当前站点前端可访问的 URL,基于 'home' 选项并自动处理协议(如 HTTPS)。它支持附加路径和指定协议方案,是 WordPress 中获取主页链接的核心函数。

关键要点

  • 返回当前站点的主页 URL,协议根据 is_ssl() 自动确定,但可通过 $scheme 参数覆盖
  • 接受两个可选参数:$path(相对路径)和 $scheme(协议方案,如 'http'、'https'、'relative'、'rest' 或 null)
  • 内部调用 get_home_url() 函数,返回字符串类型的 URL
  • 广泛用于生成各种链接,如站点地图、自定义器 URL、RSS 源等

代码示例

$url = home_url();
echo $url;
// 输出: http://www.example.com

$url = home_url( '/' );
echo $url;
// 输出: http://www.example.com/

$url = home_url( $path = '/', $scheme = 'https' );
echo $url;
// 输出: https://www.example.com/

$url = home_url( $path = 'example', $scheme = 'relative' );
echo $url;
// 输出: /example

注意事项

  • URL 默认不带尾部斜杠,需手动添加如 home_url( '/' )
  • 建议使用 esc_url() 对输出进行转义以确保安全性
  • 自 WordPress 3.0.0 版本引入,是许多其他链接函数的基础

📄 原文内容

Retrieves the URL for the current site where the front end is accessible.

Description

Returns the ‘home’ option with the appropriate protocol. The protocol will be ‘https’ if is_ssl() evaluates to true; otherwise, it will be the same as the ‘home’ option.
If $scheme is ‘http’ or ‘https’, is_ssl() is overridden.

Parameters

$pathstringoptional
Path relative to the home URL. Default empty.
$schemestring|nulloptional
Scheme to give the home URL context. Accepts 'http', 'https', 'relative', 'rest', or null.

Default:null

Return

string Home URL link with optional path appended.

Source

function home_url( $path = '', $scheme = null ) {
	return get_home_url( null, $path, $scheme );
}

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Example

    $url = home_url();
    echo $url;

    Output: http://www.example.com

    (Note the lack of a trailing slash)

    $url = home_url( '/' );
    echo $url;

    Output: http://www.example.com/

    $url = home_url( $path = '/', $scheme = 'https' );
    echo $url;

    Output: https://www.example.com/

    $url = home_url( $path = 'example', $scheme = 'relative' );
    echo $url;

    Output: /example

  2. Skip to note 4 content

    You can also add attributes at the end of the `$path` is need be…

    $url = esc_url(home_url( '/my-page?id=123'));
    echo $url;
    
    // <a href="https://your-domain/my-page?id=123" rel="nofollow ugc">https://your-domain/my-page?id=123</a>

    but best to use esc_url() to ensure you get a clean url