函数文档

wp_enqueue_block_style()

💡 云策文档标注

概述

wp_enqueue_block_style() 函数用于为特定块(block)注册并排队样式表。其加载时机取决于主题是否启用了按需加载块样式:若启用,则在块渲染时排队;否则在块初始化时排队。

关键要点

  • 函数接受两个参数:$block_name(块名称,包括命名空间)和 $args(参数数组,遵循 wp_register_style() 的规范)。
  • 参数 $args 包含 handle、src、deps、ver、media 和 path 等键,用于定义样式表的属性和依赖。
  • 内部逻辑会根据 wp_should_load_block_assets_on_demand() 的返回值决定如何挂钩样式加载:若为真,使用 render_block 过滤器;否则使用 wp_enqueue_scripts 或 wp_footer 钩子。
  • 函数自动处理 RTL(从右到左)样式表,如果存在对应的 -rtl.css 文件,会在 RTL 环境下替换路径。
  • 在编辑器中,样式通过 enqueue_block_assets 动作确保加载。

代码示例

function twentytwentytwo_support() {
    $styled_blocks = ['post-author'];
    foreach ( $styled_blocks as $block_name ) {
        $args = array(
            'handle' => "twentytwentytwo-$block_name",
            'src'    => get_theme_file_uri( "assets/css/blocks/$block_name.css" ),
        );
        wp_enqueue_block_style( "core/$block_name", $args );
    }
}
add_action( 'after_setup_theme', 'twentytwentytwo_support' );

注意事项

  • 避免将 handle 参数设置为类似 'namespace-name-style' 的值,因为这可能与 WordPress 默认的块样式句柄冲突,导致样式无法正确排队。
  • 若希望仅当块在页面上存在时才加载 CSS,可在 functions.php 中添加 add_filter( 'should_load_separate_core_block_assets', '__return_true' );,但注意在 FSE(全站编辑)主题中可能自动处理。
  • 函数内部已挂钩 enqueue_block_assets,因此直接调用时无需额外挂钩到相同动作,否则可能无效。

📄 原文内容

Enqueues a stylesheet for a specific block.

Description

If the theme has opted-in to load block styles on demand, then the stylesheet will be enqueued on-render, otherwise when the block inits.

Parameters

$block_namestringrequired
The block-name, including namespace.
$argsarrayrequired
An array of arguments. See wp_register_style() for full information about each argument.

  • handle string
    The handle for the stylesheet.
  • src string|false
    The source URL of the stylesheet.
  • deps string[]
    Array of registered stylesheet handles this stylesheet depends on.
  • ver string|bool|null
    Stylesheet version number.
  • media string
    The media for which this stylesheet has been defined.
  • path string|null
    Absolute path to the stylesheet, so that it can potentially be inlined.

Source

function wp_enqueue_block_style( $block_name, $args ) {
	$args = wp_parse_args(
		$args,
		array(
			'handle' => '',
			'src'    => '',
			'deps'   => array(),
			'ver'    => false,
			'media'  => 'all',
		)
	);

	/**
	 * Callback function to register and enqueue styles.
	 *
	 * @param string $content When the callback is used for the render_block filter,
	 *                        the content needs to be returned so the function parameter
	 *                        is to ensure the content exists.
	 * @return string Block content.
	 */
	$callback = static function ( $content ) use ( $args ) {
		// Register the stylesheet.
		if ( ! empty( $args['src'] ) ) {
			wp_register_style( $args['handle'], $args['src'], $args['deps'], $args['ver'], $args['media'] );
		}

		// Add `path` data if provided.
		if ( isset( $args['path'] ) ) {
			wp_style_add_data( $args['handle'], 'path', $args['path'] );

			// Get the RTL file path.
			$rtl_file_path = str_replace( '.css', '-rtl.css', $args['path'] );

			// Add RTL stylesheet.
			if ( file_exists( $rtl_file_path ) ) {
				wp_style_add_data( $args['handle'], 'rtl', 'replace' );

				if ( is_rtl() ) {
					wp_style_add_data( $args['handle'], 'path', $rtl_file_path );
				}
			}
		}

		// Enqueue the stylesheet.
		wp_enqueue_style( $args['handle'] );

		return $content;
	};

	$hook = did_action( 'wp_enqueue_scripts' ) ? 'wp_footer' : 'wp_enqueue_scripts';
	if ( wp_should_load_block_assets_on_demand() ) {
		/**
		 * Callback function to register and enqueue styles.
		 *
		 * @param string $content The block content.
		 * @param array  $block   The full block, including name and attributes.
		 * @return string Block content.
		 */
		$callback_separate = static function ( $content, $block ) use ( $block_name, $callback ) {
			if ( ! empty( $block['blockName'] ) && $block_name === $block['blockName'] ) {
				return $callback( $content );
			}
			return $content;
		};

		/*
		 * The filter's callback here is an anonymous function because
		 * using a named function in this case is not possible.
		 *
		 * The function cannot be unhooked, however, users are still able
		 * to dequeue the stylesheets registered/enqueued by the callback
		 * which is why in this case, using an anonymous function
		 * was deemed acceptable.
		 */
		add_filter( 'render_block', $callback_separate, 10, 2 );
		return;
	}

	/*
	 * The filter's callback here is an anonymous function because
	 * using a named function in this case is not possible.
	 *
	 * The function cannot be unhooked, however, users are still able
	 * to dequeue the stylesheets registered/enqueued by the callback
	 * which is why in this case, using an anonymous function
	 * was deemed acceptable.
	 */
	add_filter( $hook, $callback );

	// Enqueue assets in the editor.
	add_action( 'enqueue_block_assets', $callback );
}

Changelog

Version Description
5.9.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Following the standard approach, you can enqueue your block custom styles iteratively like this. Place your block custom style sheet in /assets/css/blocks/ directory. For example, if you want to override the Post Author block Avatar and content style, create /assets/css/blocks/post-author.css and add your custom styles for the respective classes there. After that, add the following snippet to your after_setup_theme callback function which is, twentytwentytwo_support() in this example.

    function twentytwentytwo_support() {
    			/*
    			 * Load additional block styles.
    			 */
    			    $styled_blocks = ['post-author'];
    			foreach ( $styled_blocks as $block_name ) {
    				$args = array(
    					'handle' => "twentytwentytwo-$block_name",
    					'src'    => get_theme_file_uri( "assets/css/blocks/$block_name.css" ),
    				);
    				wp_enqueue_block_style( "core/$block_name", $args );
    			}
    		}

    Finally, include this in your functions.php file.

    add_action( 'after_setup_theme', 'twentytwentytwo_support' );

    post-author.css for your reference, I would like the avatar to be round and the Author name centered inline with the Avatar.

    .wp-block-post-author__avatar img {
    border-radius: 50%;
    }

    .wp-block-post-author__name {
    line-height: 2.5em;
    }

  2. Skip to note 5 content

    This function can be called directly, without hooking it to specific action, because it hooks enqueuing internally to enqueue_block_assets. If it is hooked to the same hook, it will not work.