函数文档

get_site_url()

💡 云策文档标注

概述

get_site_url() 函数用于检索 WordPress 应用文件(如 wp-blog-header.php 或 wp-admin/ 文件夹)可访问的站点 URL。它基于 'siteurl' 选项,并根据 SSL 状态或指定方案自动设置协议,支持路径附加和过滤器钩子。

关键要点

  • 返回站点 URL,默认基于 is_ssl() 自动选择 http 或 https 协议,可通过 $scheme 参数覆盖。
  • 支持多站点环境,通过 $blog_id 参数指定站点 ID,默认为当前站点。
  • 可附加相对路径,通过 $path 参数实现,路径会自动与 URL 连接。
  • 提供 'site_url' 过滤器钩子,允许开发者自定义返回的 URL。
  • 返回值不带尾部斜杠,例如 https://www.example.com。

代码示例

// 获取当前站点 URL
echo get_site_url();

// 获取指定站点 ID 的 URL,并附加路径
$url = get_site_url(2, '/wp-content/themes/');

// 强制使用 https 协议
$url = get_site_url(null, '/wp-content/themes/', 'https');

// 提取主机名部分
echo parse_url(get_site_url(), PHP_URL_HOST);

注意事项

  • 在子文件夹安装时,URL 会包含子文件夹路径,如 https://www.example.com/sub/folder。
  • 函数自 WordPress 3.0.0 版本引入,兼容多站点功能。
  • 相关函数包括 get_admin_url()、set_url_scheme() 和 switch_to_blog()。

📄 原文内容

Retrieves the URL for a given 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

$blog_idint|nulloptional
Site ID. Default null (current site).

Default:null

$pathstringoptional
Path relative to the site URL. Default empty.
$schemestring|nulloptional
Scheme to give the site URL context. Accepts 'http', 'https', 'login', 'login_post', 'admin', or 'relative'.

Default:null

Return

string Site URL link with optional path appended.

Source

function get_site_url( $blog_id = null, $path = '', $scheme = null ) {
	if ( empty( $blog_id ) || ! is_multisite() ) {
		$url = get_option( 'siteurl' );
	} else {
		switch_to_blog( $blog_id );
		$url = get_option( 'siteurl' );
		restore_current_blog();
	}

	$url = set_url_scheme( $url, $scheme );

	if ( $path && is_string( $path ) ) {
		$url .= '/' . ltrim( $path, '/' );
	}

	/**
	 * Filters the site URL.
	 *
	 * @since 2.7.0
	 *
	 * @param string      $url     The complete site URL including scheme and path.
	 * @param string      $path    Path relative to the site URL. Blank string if no path is specified.
	 * @param string|null $scheme  Scheme to give the site URL context. Accepts 'http', 'https', 'login',
	 *                             'login_post', 'admin', 'relative' or null.
	 * @param int|null    $blog_id Site ID, or null for the current site.
	 */
	return apply_filters( 'site_url', $url, $path, $scheme, $blog_id );
}

Hooks

apply_filters( ‘site_url’, string $url, string $path, string|null $scheme, int|null $blog_id )

Filters the site URL.

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 8 content

    To get just the hostname/domain component of the Site URL (without paths, schema, etc.) you could use the following:

    echo parse_url( get_site_url(), PHP_URL_HOST );