函数文档

wp_get_global_styles()

💡 云策文档标注

概述

wp_get_global_styles() 函数用于获取合并核心、主题和用户数据后的样式。它支持通过路径和上下文参数来检索特定样式或所有样式,适用于 WordPress 主题和块编辑器开发。

关键要点

  • 函数返回合并后的样式数组或单个样式值,基于核心、主题和用户数据的整合。
  • 参数 $path 可选,指定要检索的样式路径;为空时返回所有样式。
  • 参数 $context 可选,包含 block_name、origin 和 transforms 等元数据,用于控制样式来源和转换。
  • origin 参数有效值为 'all'(默认,包含核心、主题和用户)或 'base'(仅核心和主题)。
  • transforms 参数支持 'resolve-variables' 转换,用于解析 CSS 变量到实际值。
  • 函数内部使用 WP_Theme_JSON_Resolver::get_merged_data() 和 WP_Theme_JSON::resolve_variables() 处理数据。
  • 从 WordPress 5.9.0 版本引入,6.3.0 版本增强了 transforms 参数的功能。

代码示例

// 获取 'core/button' 块的颜色样式,并解析变量
wp_get_global_styles(
    array('color'),
    array(
        'block_name' => 'core/button',
        'transforms' => array('resolve-variables')
    )
);
// 返回示例数组:['background' => '#113AF5', 'text' => '#FFFFFF']

注意事项

  • 确保 $context 参数中的 origin 和 transforms 设置正确,以避免意外行为。
  • 函数依赖于 WP_Theme_JSON 相关类,需在支持全局样式的 WordPress 环境中使用。
  • 用户贡献的笔记提供了实际使用示例,可作为开发参考。

📄 原文内容

Gets the styles resulting of merging core, theme, and user data.

Parameters

$patharrayoptional
Path to the specific style to retrieve. Optional.
If empty, will return all styles.

Default:array()

$contextarrayoptional
Metadata to know where to retrieve the $path from. Optional.

  • block_name string
    Which block to retrieve the styles from.
    If empty, it’ll return the styles for the global context.
  • origin string
    Which origin to take data from.
    Valid values are 'all' (core, theme, and user) or 'base' (core and theme).
    If empty or unknown, 'all' is used.
  • transforms array
    Which transformation(s) to apply.
    Valid value is array( 'resolve-variables' ).
    If defined, variables are resolved to their value in the styles.

Default:array()

Return

mixed The styles array or individual style value to retrieve.

Source

function wp_get_global_styles( $path = array(), $context = array() ) {
	if ( ! empty( $context['block_name'] ) ) {
		$path = array_merge( array( 'blocks', $context['block_name'] ), $path );
	}

	$origin = 'custom';
	if ( isset( $context['origin'] ) && 'base' === $context['origin'] ) {
		$origin = 'theme';
	}

	$resolve_variables = isset( $context['transforms'] )
	&& is_array( $context['transforms'] )
	&& in_array( 'resolve-variables', $context['transforms'], true );

	$merged_data = WP_Theme_JSON_Resolver::get_merged_data( $origin );
	if ( $resolve_variables ) {
		$merged_data = WP_Theme_JSON::resolve_variables( $merged_data );
	}
	$styles = $merged_data->get_raw_data()['styles'];
	return _wp_array_get( $styles, $path, $styles );
}

Changelog

Version Description
6.3.0 transforms is now usable in the context parameter. In case [transforms]['resolve_variables'] is defined, variables are resolved to their value in the styles.
5.9.0 Introduced.

User Contributed Notes