函数文档

get_stylesheet_directory_uri()

💡 云策文档标注

概述

get_stylesheet_directory_uri() 函数用于获取当前活动主题(包括子主题)的样式表目录的 URI。它返回一个格式正确的 URI,适用于链接、引用样式表或图像等场景。

关键要点

  • 返回活动主题的样式表目录 URI,格式为 web 地址(如 http:// 或 https://),不包含尾部斜杠。
  • 当使用子主题时,返回子主题的目录 URI;如需父主题 URI,应使用 get_template_directory_uri()。
  • 适用于 HTML 引用,如链接或图像;若需在 PHP 中包含本地文件,应使用 get_stylesheet_directory()。
  • 可通过 'stylesheet_directory_uri' 过滤器钩子进行自定义过滤。

代码示例

// 获取当前主题的样式表目录 URI
$stylesheet_uri = get_stylesheet_directory_uri();
echo $stylesheet_uri; // 输出类似:https://example.com/wp-content/themes/mytheme

注意事项

  • 返回的 URI 不包含尾部斜杠,使用时需注意拼接路径。
  • 在 HTML 属性(如 src)中使用时,建议对返回的 URI 进行转义,特别是当添加额外文件路径时。

📄 原文内容

Retrieves stylesheet directory URI for the active theme.

Return

string URI to active theme’s stylesheet directory.

More Information

  • The returned URI does not contain a trailing slash.
  • This function returns a properly-formed URI; in other words, it will be a web-address (starting with http:// or https:// for SSL). As such, it is most appropriately used for links, referencing additional stylesheets, or probably most commonly, images.
  • In the event a child theme is being used, this function will return the child’s theme directory URI. Use get_template_directory_uri() to avoid being overridden by a child theme.
  • If you want to include a local file in PHP, use get_stylesheet_directory() instead.

Source

function get_stylesheet_directory_uri() {
	$stylesheet         = str_replace( '%2F', '/', rawurlencode( get_stylesheet() ) );
	$theme_root_uri     = get_theme_root_uri( $stylesheet );
	$stylesheet_dir_uri = "$theme_root_uri/$stylesheet";

	/**
	 * Filters the stylesheet directory URI.
	 *
	 * @since 1.5.0
	 *
	 * @param string $stylesheet_dir_uri Stylesheet directory URI.
	 * @param string $stylesheet         Name of the activated theme's directory.
	 * @param string $theme_root_uri     Themes root URI.
	 */
	return apply_filters( 'stylesheet_directory_uri', $stylesheet_dir_uri, $stylesheet, $theme_root_uri );
}

Hooks

apply_filters( ‘stylesheet_directory_uri’, string $stylesheet_dir_uri, string $stylesheet, string $theme_root_uri )

Filters the stylesheet directory URI.

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes