get_theme_root()
云策文档标注
概述
get_theme_root() 函数用于检索 WordPress 主题目录的绝对路径。它支持可选参数指定特定主题,并确保路径格式正确,无尾部斜杠。
关键要点
- 函数返回主题目录的绝对路径,默认基于 WP_CONTENT_DIR 常量。
- 可选参数 $stylesheet_or_template 可指定主题名称,以获取其对应的主题根目录。
- 路径不包含尾部斜杠,符合 WordPress 文件路径规范。
- 内部使用 get_raw_theme_root() 获取原始路径,并应用 'theme_root' 过滤器进行自定义。
- 如果未指定主题或路径无效,则回退到默认的 WP_CONTENT_DIR . '/themes'。
代码示例
// 获取默认主题目录路径
$theme_root = get_theme_root();
// 获取特定主题的目录路径
$specific_theme_root = get_theme_root('twentytwenty');注意事项
- 函数不返回尾部斜杠,使用时需注意路径拼接。
- 主题目录路径可通过 'theme_root' 过滤器进行修改,允许开发者自定义路径。
- 参数 $stylesheet_or_template 为空时,函数返回主主题根目录,即 WP_CONTENT_DIR . '/themes'。
原文内容
Retrieves path to themes directory.
Description
Does not have trailing slash.
Parameters
$stylesheet_or_templatestringoptional-
The stylesheet or template name of the theme.
Default is to leverage the main theme root.
Source
function get_theme_root( $stylesheet_or_template = '' ) {
global $wp_theme_directories;
$theme_root = '';
if ( $stylesheet_or_template ) {
$theme_root = get_raw_theme_root( $stylesheet_or_template );
if ( $theme_root ) {
/*
* Always prepend WP_CONTENT_DIR unless the root currently registered as a theme directory.
* This gives relative theme roots the benefit of the doubt when things go haywire.
*/
if ( ! in_array( $theme_root, (array) $wp_theme_directories, true ) ) {
$theme_root = WP_CONTENT_DIR . $theme_root;
}
}
}
if ( ! $theme_root ) {
$theme_root = WP_CONTENT_DIR . '/themes';
}
/**
* Filters the absolute path to the themes directory.
*
* @since 1.5.0
*
* @param string $theme_root Absolute path to themes directory.
*/
return apply_filters( 'theme_root', $theme_root );
}
Hooks
- apply_filters( ‘theme_root’, string $theme_root )
-
Filters the absolute path to the themes directory.
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 2 content
Codex
Number of Subdirectories in Themes Directory
The function below informs about the number of subdirectories in the themes directory. Note that this doesn’t necessarily match the number of themes recognized by WordPress.
Example output:
There are 5 subdirectories in the /home/user/public_html/wp-content/themes directory.