get_theme_file_path()
云策文档标注
概述
get_theme_file_path() 函数用于检索主题中文件的路径,优先在子主题目录中查找,支持子主题覆盖父主题文件。
关键要点
- 函数优先搜索 stylesheet 目录(子主题),再搜索 template 目录(父主题),便于子主题覆盖文件。
- 参数 $file 可选,指定要搜索的文件名;返回文件路径字符串。
- 通过 apply_filters('theme_file_path', $path, $file) 钩子可过滤文件路径。
- 相关函数包括 get_stylesheet_directory() 和 get_template_directory()。
代码示例
get_theme_file_path( '/inc/template-functions.php' );
原文内容
Retrieves the path of a file in the theme.
Description
Searches in the stylesheet directory before the template directory so themes which inherit from a parent theme can just override one file.
Parameters
$filestringoptional-
File to search for in the stylesheet directory.
Source
function get_theme_file_path( $file = '' ) {
$file = ltrim( $file, '/' );
$stylesheet_directory = get_stylesheet_directory();
$template_directory = get_template_directory();
if ( empty( $file ) ) {
$path = $stylesheet_directory;
} elseif ( $stylesheet_directory !== $template_directory && file_exists( $stylesheet_directory . '/' . $file ) ) {
$path = $stylesheet_directory . '/' . $file;
} else {
$path = $template_directory . '/' . $file;
}
/**
* Filters the path to a file in the theme.
*
* @since 4.7.0
*
* @param string $path The file path.
* @param string $file The requested file to search for.
*/
return apply_filters( 'theme_file_path', $path, $file );
}
Hooks
- apply_filters( ‘theme_file_path’, string $path, string $file )
-
Filters the path to a file in the theme.
Changelog
| Version | Description |
|---|---|
| 4.7.0 | Introduced. |
Skip to note 2 content
Sushil Adhikari
We can use this function to allow child theme to overwrite the functional file of the parent theme.
get_theme_file_path( '/inc/template-functions.php' );Thanks