register_block_style()
云策文档标注
概述
register_block_style() 函数用于在 WordPress 中注册新的块样式,允许开发者自定义块的外观。它通过 WP_Block_Styles_Registry 类实现,支持为单个或多个块类型添加样式。
关键要点
- 函数接受两个参数:$block_name(块类型名称或数组)和 $style_properties(样式属性数组)。
- $style_properties 数组必须包含 name 和 label 属性,可选属性包括 inline_style、style_handle、style_data 和 is_default。
- 函数返回布尔值,表示注册是否成功。
- 从 WordPress 6.6.0 开始支持为多个块类型注册样式。
- 使用前应检查函数是否存在,以确保兼容性。
代码示例
if ( function_exists( 'register_block_tyle' ) ) {
register_block_style(
'core/quote',
array(
'name' => 'blue-quote',
'label' => __( 'Blue Quote', 'textdomain' ),
'is_default' => true,
'inline_style' => '.wp-block-quote.is-style-blue-quote { color: blue; }',
)
);
}注意事项
- inline_style 属性中的 CSS 类不应手动添加 "is-style-" 前缀,系统会自动处理。
- 可以通过浏览器控制台使用 wp.blocks.getBlockTypes() 查找正确的块名称。
- 样式注册后,CSS 将根据 inline_style 或 style_handle 选项加载到页面头部。
原文内容
Registers a new block style.
Parameters
$block_namestring|string[]required-
Block type name including namespace or array of namespaced block type names.
$style_propertiesarrayrequired-
Array containing the properties of the style name, label, style_handle (name of the stylesheet to be enqueued), inline_style (string containing the CSS to be added), style_data (theme.json-like array to generate CSS from).
See WP_Block_Styles_Registry::register().
Source
function register_block_style( $block_name, $style_properties ) {
return WP_Block_Styles_Registry::get_instance()->register( $block_name, $style_properties );
}
Skip to note 2 content
Marcio Duarte
The only mandatory properties of the
$style_propertiesarray arenameandlabel:name: the identifier of the style used to compute a CSS class.label: a human-readable label for the style.The array can optionally include
inline_styleorstyle_handle, in order to choose how to load the required CSS:inline_style: contains inline CSS code that registers the CSS class required for the style. All inline block styles will appear in theheadtag.style_handle: contains the handle to an already registered style that should be enqueued in places where block styles are needed. Using this option gives you more control over where to enqueue the CSS.Also optional: set the
is_defaultproperty totrueto mark one of the block styles as the default one.Tip: to find the correct block name, open the block editor, launch the browser console and type
wp.blocks.getBlockTypes(). You will see the complete list of block names (from core or third-party).Complete example:
if ( function_exists( 'register_block_style' ) ) { register_block_style( 'core/quote', array( 'name' => 'blue-quote', 'label' => __( 'Blue Quote', 'textdomain' ), 'is_default' => true, 'inline_style' => '.wp-block-quote.is-style-blue-quote { color: blue; }', ) ); }For more information, see the Developer Handbook.