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.
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. |
Skip to note 5 content
Florian Simeth
This function returns the URL to the current child theme if a child theme is used. If you want to return the URL to the root/mother theme, use get_template_directory_uri() instead.
Skip to note 6 content
Codex
Image (HTML)
<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/aternus.png" alt="" width="" height="" />Skip to note 7 content
surwan
Given –
Website URL:
https://example.com/Active theme folder:
mythemeThis function returns the following string:
https://example.com/wp-content/themes/mythemeNOTE: without trailing slash (/)
Skip to note 8 content
Rami Yushuvaev
When using inside HTML `src` attribute, you should escape the returned URL when you add some files after the function:
<script async type="text/javascript" src="<?php echo esc_url( get_stylesheet_directory_uri() . '/dist/main.js' ); ?>"> </script>