函数文档

get_stylesheet_directory()

💡 云策文档标注

概述

get_stylesheet_directory() 函数用于获取当前活动主题的样式表目录路径,返回字符串类型。当使用子主题时,返回子主题目录路径,而非父主题目录。

关键要点

  • 返回活动主题的样式表目录绝对路径,不包含尾部斜杠
  • 若使用子主题,返回子主题目录路径;获取父主题目录应使用 get_template_directory()
  • 可通过 apply_filters('stylesheet_directory', ...) 钩子过滤路径
  • 相关函数包括 get_stylesheet_directory_uri() 用于获取 URI,get_template_directory() 用于父主题路径

代码示例

// 示例输出:/home/user/public_html/wp-content/themes/my_theme
$stylesheet_dir = get_stylesheet_directory();

注意事项

  • 路径不包含尾部斜杠,使用时需注意拼接
  • 优先使用函数而非 STYLESHEETPATH 常量,以支持过滤钩子
  • 在子主题环境中,确保理解与父主题路径的区别

📄 原文内容

Retrieves stylesheet directory path for the active theme.

Return

string Path to active theme’s stylesheet directory.

More Information

Source

function get_stylesheet_directory() {
	$stylesheet     = get_stylesheet();
	$theme_root     = get_theme_root( $stylesheet );
	$stylesheet_dir = "$theme_root/$stylesheet";

	/**
	 * Filters the stylesheet directory path for the active theme.
	 *
	 * @since 1.5.0
	 *
	 * @param string $stylesheet_dir Absolute path to the active theme.
	 * @param string $stylesheet     Directory name of the active theme.
	 * @param string $theme_root     Absolute path to themes directory.
	 */
	return apply_filters( 'stylesheet_directory', $stylesheet_dir, $stylesheet, $theme_root );
}

Hooks

apply_filters( ‘stylesheet_directory’, string $stylesheet_dir, string $stylesheet, string $theme_root )

Filters the stylesheet directory path for the active theme.

Changelog

Version Description
6.4.2 Memoization removed.
6.4.0 Memoizes filter execution so that it only runs once for the current theme.
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 5 content

    You can also use the constant “STYLESHEETPATH” in replacement of get_stylesheet_directory()

  2. Skip to note 6 content

    get_stylesheet_directory() retrieves the child-theme’s directory.
    If you want to retrieve the parent-theme’s directory use get_template_directory() instead or even better loacate_template() – This way WordPress automatically uses your child themes directory to look for your resource – if there is a child-theme-file present it will use this one instead. No need for enqueuing anything.