style_loader_src
云策文档标注
概述
style_loader_src 是一个 WordPress 过滤器,用于修改已入队样式表的完整 URL。它允许开发者在样式表 URL 被输出前进行自定义处理,如移除或添加查询参数。
关键要点
- 过滤器名称:style_loader_src
- 参数:$src(样式表的源 URL 字符串)和 $handle(样式表的注册句柄字符串)
- 用途:常用于优化静态文件缓存、更新版本号或动态调整样式表路径
- 引入版本:WordPress 2.6.0
代码示例
// 移除静态 CSS 文件的查询字符串
function remove_query_string_from_static_files( $src ) {
if( strpos( $src, '?ver=' ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
add_filter( 'style_loader_src', 'remove_query_string_from_static_files', 10, 2 );// 更新子主题样式表的版本号
function wpdocs_update_stylesheet_version( $src, $handle ) {
if ( ! strcmp( $handle, 'wpdocs-style' ) ) {
$src = get_stylesheet_uri();
$src = add_query_arg( 'ver', '6.0.0', $src );
}
return $src;
}
add_filter( 'style_loader_src', 'wpdocs_update_stylesheet_version', 10, 2 );注意事项
- 使用此过滤器时需确保正确处理 $handle 参数,以避免影响其他样式表
- 示例代码展示了移除查询字符串和添加自定义版本号的常见应用场景
原文内容
Filters an enqueued style’s fully-qualified URL.
Parameters
$srcstring-
The source URL of the enqueued style.
$handlestring-
The style’s registered handle.
Source
$src = apply_filters( 'style_loader_src', $src, $handle );
Changelog
| Version | Description |
|---|---|
| 2.6.0 | Introduced. |
Skip to note 3 content
Ravi Makwana
// Remove query string from static CSS files function remove_query_string_from_static_files( $src ) { if( strpos( $src, '?ver=' ) ) $src = remove_query_arg( 'ver', $src ); return $src; } add_filter( 'style_loader_src', 'remove_query_string_from_static_files', 10, 2 );Skip to note 4 content
Anthony Hortin
If you have a child theme that has had its stylesheet enqueued from within the main Parent theme, and you wish to update the version number that’s appended to the url, you can include this in your child theme
functions.phpfile.Obviously, change the version number (‘6.0.0’ in this example) to whatever is appropriate for you, along with comparing the approriate stylesheet handle (‘wpdocs-style’ in this example)
Where:
$src – (string) The source URL of the enqueued style
$handle – (string) The style’s registered handle
/** * Update the version number on our child theme stylesheet, that's been enqueued from within the parent theme */ function wpdocs_update_stylesheet_version( $src, $handle ) { if ( ! strcmp( $handle, 'wpdocs-style' ) ) { $src = get_stylesheet_uri(); $src = add_query_arg( 'ver', '6.0.0', $src ); } return $src; } add_filter( 'style_loader_src', 'wpdocs_update_stylesheet_version', 10, 2 );