函数文档

enqueue_editor_block_styles_assets()

💡 云策文档标注

概述

enqueue_editor_block_styles_assets() 函数用于在编辑器中注册和入队块样式所需的脚本资产。它通过 WP_Block_Styles_Registry 获取所有已注册的块样式,并生成内联脚本来调用 wp.blocks.registerBlockStyle() 进行注册。

关键要点

  • 函数负责入队编辑器块样式功能所需的资产
  • 使用 WP_Block_Styles_Registry::get_instance()->get_all_registered() 获取所有已注册的块样式
  • 通过 wp.blocks.registerBlockStyle() 动态注册块样式到 JavaScript 环境
  • 依赖 wp-blocks 脚本,并注册一个名为 wp-block-styles 的脚本以添加内联代码
  • 在 WordPress 5.3.0 版本中引入

代码示例

function enqueue_editor_block_styles_assets() {
	$block_styles = WP_Block_Styles_Registry::get_instance()->get_all_registered();

	$register_script_lines = array( '( function() {' );
	foreach ( $block_styles as $block_name => $styles ) {
		foreach ( $styles as $style_properties ) {
			$block_style = array(
				'name'  => $style_properties['name'],
				'label' => $style_properties['label'],
			);
			if ( isset( $style_properties['is_default'] ) ) {
				$block_style['isDefault'] = $style_properties['is_default'];
			}
			$register_script_lines[] = sprintf(
				'twp.blocks.registerBlockStyle( '%s', %s );',
				$block_name,
				wp_json_encode( $block_style, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES )
			);
		}
	}
	$register_script_lines[] = '} )();';
	$inline_script           = implode( "n", $register_script_lines );

	wp_register_script( 'wp-block-styles', false, array( 'wp-blocks' ), true, array( 'in_footer' => true ) );
	wp_add_inline_script( 'wp-block-styles', $inline_script );
	wp_enqueue_script( 'wp-block-styles' );
}

注意事项

  • 函数依赖于 wp-blocks 脚本,确保在调用前已正确加载
  • 使用 wp_json_encode() 处理 JSON 编码,需注意参数设置以避免安全问题
  • 脚本注册时设置 in_footer 为 true,可能影响加载时机

📄 原文内容

Function responsible for enqueuing the assets required for block styles functionality on the editor.

Source

function enqueue_editor_block_styles_assets() {
	$block_styles = WP_Block_Styles_Registry::get_instance()->get_all_registered();

	$register_script_lines = array( '( function() {' );
	foreach ( $block_styles as $block_name => $styles ) {
		foreach ( $styles as $style_properties ) {
			$block_style = array(
				'name'  => $style_properties['name'],
				'label' => $style_properties['label'],
			);
			if ( isset( $style_properties['is_default'] ) ) {
				$block_style['isDefault'] = $style_properties['is_default'];
			}
			$register_script_lines[] = sprintf(
				'	wp.blocks.registerBlockStyle( '%s', %s );',
				$block_name,
				wp_json_encode( $block_style, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES )
			);
		}
	}
	$register_script_lines[] = '} )();';
	$inline_script           = implode( "n", $register_script_lines );

	wp_register_script( 'wp-block-styles', false, array( 'wp-blocks' ), true, array( 'in_footer' => true ) );
	wp_add_inline_script( 'wp-block-styles', $inline_script );
	wp_enqueue_script( 'wp-block-styles' );
}

Changelog

Version Description
5.3.0 Introduced.