wp_get_global_styles_custom_css()
云策文档标注
概述
wp_get_global_styles_custom_css() 函数用于从 theme.json 获取全局样式的自定义 CSS,但已在 WordPress 6.7.0 版本中被弃用。它通过缓存机制优化性能,并确保数据在开发模式下保持最新。
关键要点
- 函数已弃用:自 WordPress 6.7.0 起,推荐使用 wp_get_global_stylesheet 获取顶级自定义 CSS,或 WP_Theme_JSON::get_styles_for_block 获取块级自定义 CSS。
- 返回类型:函数返回字符串,即全局样式的自定义 CSS;如果主题没有 theme.json 文件,则返回空字符串。
- 缓存机制:使用 wp_cache_get 和 wp_cache_set 进行非持久性缓存,缓存组为 'theme_json',以提高性能并避免干扰主题开发工作流。
- 开发模式处理:当开发模式设置为 'theme' 时,忽略缓存以确保数据实时更新。
- 依赖检查:函数内部调用 wp_theme_has_theme_json() 检查主题是否包含 theme.json 文件。
代码示例
// 示例:获取全局样式的自定义 CSS
$custom_css = wp_get_global_styles_custom_css();
if ( ! empty( $custom_css ) ) {
echo $custom_css;
}注意事项
- 弃用警告:使用此函数会触发 _deprecated_function() 警告,建议尽快迁移到新函数。
- 缓存策略:缓存是非持久性的,旨在适应通过 Hook 动态修改 theme.json 数据的需求,如相关过滤器所示。
- 性能考虑:在开发模式下禁用缓存,以避免影响主题开发者的调试过程。
原文内容
Gets the global styles custom CSS from theme.json.
Source
function wp_get_global_styles_custom_css() {
_deprecated_function( __FUNCTION__, '6.7.0', 'wp_get_global_stylesheet' );
if ( ! wp_theme_has_theme_json() ) {
return '';
}
/*
* Ignore cache when the development mode is set to 'theme', so it doesn't interfere with the theme
* developer's workflow.
*/
$can_use_cached = ! wp_is_development_mode( 'theme' );
/*
* By using the 'theme_json' group, this data is marked to be non-persistent across requests.
* @see `wp_cache_add_non_persistent_groups()`.
*
* The rationale for this is to make sure derived data from theme.json
* is always fresh from the potential modifications done via hooks
* that can use dynamic data (modify the stylesheet depending on some option,
* settings depending on user permissions, etc.).
* See some of the existing hooks to modify theme.json behavior:
* @see https://make.wordpress.org/core/2022/10/10/filters-for-theme-json-data/
*
* A different alternative considered was to invalidate the cache upon certain
* events such as options add/update/delete, user meta, etc.
* It was judged not enough, hence this approach.
* @see https://github.com/WordPress/gutenberg/pull/45372
*/
$cache_key = 'wp_get_global_styles_custom_css';
$cache_group = 'theme_json';
if ( $can_use_cached ) {
$cached = wp_cache_get( $cache_key, $cache_group );
if ( $cached ) {
return $cached;
}
}
$tree = WP_Theme_JSON_Resolver::get_merged_data();
$stylesheet = $tree->get_custom_css();
if ( $can_use_cached ) {
wp_cache_set( $cache_key, $stylesheet, $cache_group );
}
return $stylesheet;
}
Changelog
| Version | Description |
|---|---|
| 6.7.0 | Deprecated. Use ‘wp_get_global_stylesheet’ instead for top-level custom CSS, or ‘WP_Theme_JSON::get_styles_for_block’ for block-level custom CSS. |
| 6.2.0 | Introduced. |