函数文档

enqueue_block_styles_assets()

💡 云策文档标注

概述

enqueue_block_styles_assets() 函数用于在编辑器和前端为块样式功能加载所需的样式。它根据块样式注册信息,动态处理样式表和内联样式的加载。

关键要点

  • 函数从 WP_Block_Styles_Registry 获取所有已注册的块样式。
  • 根据 wp_should_load_block_assets_on_demand() 的返回值,决定样式是按需加载还是直接加载。
  • 支持通过 style_handle 注册样式表,使用 wp_enqueue_style() 加载。
  • 支持通过 inline_style 添加内联样式,使用 wp_add_inline_style() 附加到相应句柄。
  • 按需加载时,通过 add_filter() 在 render_block 钩子中动态加载样式。

代码示例

function mytheme_block_assets() {
    wp_deregister_style( 'wp-block-library' );
    wp_register_style( 'wp-block-library', '' );
}
add_action( 'enqueue_block_assets', 'mytheme_block_assets' );

注意事项

  • 此函数在 WordPress 5.3.0 版本中引入。
  • 相关函数包括 wp_should_load_block_assets_on_demand()、generate_block_asset_handle() 等,用于辅助样式加载逻辑。
  • 开发者可以通过 deregister 和 register 样式来定制核心块样式的加载行为。

📄 原文内容

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

Source

function enqueue_block_styles_assets() {
	global $wp_styles;

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

	foreach ( $block_styles as $block_name => $styles ) {
		foreach ( $styles as $style_properties ) {
			if ( isset( $style_properties['style_handle'] ) ) {

				// If the site loads block styles on demand, enqueue the stylesheet on render.
				if ( wp_should_load_block_assets_on_demand() ) {
					add_filter(
						'render_block',
						static function ( $html, $block ) use ( $block_name, $style_properties ) {
							if ( $block['blockName'] === $block_name ) {
								wp_enqueue_style( $style_properties['style_handle'] );
							}
							return $html;
						},
						10,
						2
					);
				} else {
					wp_enqueue_style( $style_properties['style_handle'] );
				}
			}
			if ( isset( $style_properties['inline_style'] ) ) {

				// Default to "wp-block-library".
				$handle = 'wp-block-library';

				// If the site loads block styles on demand, check if the block has a stylesheet registered.
				if ( wp_should_load_block_assets_on_demand() ) {
					$block_stylesheet_handle = generate_block_asset_handle( $block_name, 'style' );

					if ( isset( $wp_styles->registered[ $block_stylesheet_handle ] ) ) {
						$handle = $block_stylesheet_handle;
					}
				}

				// Add inline styles to the calculated handle.
				wp_add_inline_style( $handle, $style_properties['inline_style'] );
			}
		}
	}
}

Changelog

Version Description
5.3.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    If you want opt-out of loading CSS for the core blocks, loaded in the wp-block-library stylesheet, you can do so by the following:

    function mytheme_block_assets() {
    	wp_deregister_style( 'wp-block-library' );
    	wp_register_style( 'wp-block-library', '' );
    }
    add_action( 'enqueue_block_assets', 'mytheme_block_assets' );

    (credit to Adam Jacobi and Brad Thomason )