get_theme_file_uri()
云策文档标注
概述
get_theme_file_uri() 函数用于检索主题中文件的 URL,优先在子主题样式表目录中查找,支持主题继承和文件覆盖。
关键要点
- 函数返回主题文件的 URL,参数 $file 可选,为空时返回样式表目录 URI
- 搜索顺序:先检查子主题样式表目录,若文件不存在则回退到父主题模板目录
- 通过 apply_filters('theme_file_uri', $url, $file) 钩子可过滤返回的 URL
- 相关函数包括 get_stylesheet_directory()、get_template_directory_uri() 等,用于路径和 URI 获取
- 自 WordPress 4.7.0 版本引入,常用于主题开发中加载本地资源
代码示例
// 示例:在主题中加载自定义 CSS 文件
wp_enqueue_style( 'custom-font-awesome', get_theme_file_uri('/css/all.min.css'), array() );注意事项
- 适用于主题继承场景,子主题可覆盖父主题文件
- 可用于块模式、主题样式等场景,如 WP_Theme_JSON_Resolver 和 WP_Font_Face_Resolver 中使用
原文内容
Retrieves the URL 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_uri( $file = '' ) {
$file = ltrim( $file, '/' );
$stylesheet_directory = get_stylesheet_directory();
if ( empty( $file ) ) {
$url = get_stylesheet_directory_uri();
} elseif ( get_template_directory() !== $stylesheet_directory && file_exists( $stylesheet_directory . '/' . $file ) ) {
$url = get_stylesheet_directory_uri() . '/' . $file;
} else {
$url = get_template_directory_uri() . '/' . $file;
}
/**
* Filters the URL to a file in the theme.
*
* @since 4.7.0
*
* @param string $url The file URL.
* @param string $file The requested file to search for.
*/
return apply_filters( 'theme_file_uri', $url, $file );
}
Hooks
- apply_filters( ‘theme_file_uri’, string $url, string $file )
-
Filters the URL to a file in the theme.
Changelog
| Version | Description |
|---|---|
| 4.7.0 | Introduced. |
Skip to note 3 content
Marcio Duarte
You can use this function to include local theme assets (like images) in your block patterns:
<!-- wp:image {"id":12,"width":640,"height":400,"sizeSlug":"full","linkDestination":"none"} --> <figure class="wp-block-image size-full"><img src="<?php echo esc_url( get_theme_file_uri( 'assets/img/my-asset.png' ) ); ?>" alt="<?php _e( 'Asset description' ) ?>" width="640" height="400"/></figure> <!-- /wp:image -->Skip to note 4 content
Marcio Zebedeu
a simple example
wp_enqueue_style ( 'custom-font-awesome', get_theme_file_uri('/css/all.min.css'), array () );