_wp_normalize_relative_css_links()
云策文档标注
概述
_wp_normalize_relative_css_links() 函数用于将 CSS 中的 URL 转换为相对于 WordPress 安装目录的路径。它通过正则表达式匹配并处理 CSS 字符串中的 URL,确保资源引用正确。
关键要点
- 函数接受两个参数:$css(CSS 字符串)和 $stylesheet_url(样式表 URL),返回处理后的 CSS 字符串。
- 使用 preg_replace_callback 匹配 CSS 中的 url() 声明,并基于 $stylesheet_url 计算相对路径。
- 对于以 http:、https:、/、# 或 data: 开头的 URL,函数会跳过处理,保持原样。
- 内部调用 wp_make_link_relative() 将绝对 URL 转换为相对于站点根目录的路径。
- 该函数自 WordPress 5.9.0 版本引入,主要用于 wp_maybe_inline_styles() 以支持内联样式。
代码示例
function _wp_normalize_relative_css_links( $css, $stylesheet_url ) {
return preg_replace_callback(
'#(urls*(s*['"']?s*)([^'")]+)#',
static function ( $matches ) use ( $stylesheet_url ) {
list( , $prefix, $url ) = $matches;
// Short-circuit if the URL does not require normalization.
if (
str_starts_with( $url, 'http:' ) ||
str_starts_with( $url, 'https:' ) ||
str_starts_with( $url, '/' ) ||
str_starts_with( $url, '#' ) ||
str_starts_with( $url, 'data:' )
) {
return $matches[0];
}
// Build the absolute URL.
$absolute_url = dirname( $stylesheet_url ) . '/' . $url;
$absolute_url = str_replace( '/./', '/', $absolute_url );
// Convert to URL related to the site root.
$url = wp_make_link_relative( $absolute_url );
return $prefix . $url;
},
$css
);
}
原文内容
Makes URLs relative to the WordPress installation.
Parameters
$cssstringrequired-
The CSS to make URLs relative to the WordPress installation.
$stylesheet_urlstringrequired-
The URL to the stylesheet.
Source
function _wp_normalize_relative_css_links( $css, $stylesheet_url ) {
return preg_replace_callback(
'#(urls*(s*['"]?s*)([^'")]+)#',
static function ( $matches ) use ( $stylesheet_url ) {
list( , $prefix, $url ) = $matches;
// Short-circuit if the URL does not require normalization.
if (
str_starts_with( $url, 'http:' ) ||
str_starts_with( $url, 'https:' ) ||
str_starts_with( $url, '/' ) ||
str_starts_with( $url, '#' ) ||
str_starts_with( $url, 'data:' )
) {
return $matches[0];
}
// Build the absolute URL.
$absolute_url = dirname( $stylesheet_url ) . '/' . $url;
$absolute_url = str_replace( '/./', '/', $absolute_url );
// Convert to URL related to the site root.
$url = wp_make_link_relative( $absolute_url );
return $prefix . $url;
},
$css
);
}
Changelog
| Version | Description |
|---|---|
| 5.9.0 | Introduced. |