函数文档

network_site_url()

💡 云策文档标注

概述

network_site_url() 函数用于获取当前网络的站点 URL,支持添加相对路径和指定协议方案。在非多站点环境下,它会回退到 site_url() 函数。

关键要点

  • 返回当前网络的站点 URL,根据 is_ssl() 自动选择 'http' 或 'https' 协议,除非通过 $scheme 参数覆盖。
  • 接受两个可选参数:$path(相对路径,默认为空字符串)和 $scheme(协议方案,可接受 'http'、'https' 或 'relative',默认为 null)。
  • 在多站点环境中,使用 get_network() 获取网络数据,并应用 set_url_scheme() 设置协议。
  • 提供 'network_site_url' 过滤器钩子,允许开发者修改返回的 URL。
  • 相关函数包括 get_network()、set_url_scheme()、site_url()、is_multisite() 和 apply_filters()。

代码示例

// 获取当前站点的 URL(基本用法)
$url = network_site_url();
echo $url; // 输出: http://www.example.com/wordpress/

// 获取指定页面的安全 URL
$url = network_site_url('/contact-us/', 'https');
echo $url; // 输出: https://www.example.com/contact-us/

注意事项

  • 如果 WordPress 安装在子目录(如 /wp/site1/),网络路径可能包含 'wp/',使用时需注意路径处理。
  • 在非多站点环境下,此函数直接调用 site_url(),确保兼容性。

📄 原文内容

Retrieves the site URL for the current network.

Description

Returns the site URL with the appropriate protocol, ‘https’ if is_ssl() and ‘http’ otherwise. If $scheme is ‘http’ or ‘https’, is_ssl() is overridden.

See also

Parameters

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

Default:null

Return

string Site URL link with optional path appended.

Source

function network_site_url( $path = '', $scheme = null ) {
	if ( ! is_multisite() ) {
		return site_url( $path, $scheme );
	}

	$current_network = get_network();

	if ( 'relative' === $scheme ) {
		$url = $current_network->path;
	} else {
		$url = set_url_scheme( 'http://' . $current_network->domain . $current_network->path, $scheme );
	}

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

	/**
	 * Filters the network site URL.
	 *
	 * @since 3.0.0
	 *
	 * @param string      $url    The complete network site URL including scheme and path.
	 * @param string      $path   Path relative to the network site URL. Blank string if
	 *                            no path is specified.
	 * @param string|null $scheme Scheme to give the URL context. Accepts 'http', 'https',
	 *                            'relative' or null.
	 */
	return apply_filters( 'network_site_url', $url, $path, $scheme );
}

Hooks

apply_filters( ‘network_site_url’, string $url, string $path, string|null $scheme )

Filters the network site URL.

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes