WordPress函数:wp_enqueue_block_style 为特定块引入样式表

江河/ 02月02日/ WordPress/ 浏览 412

函数原型:


wp_enqueue_block_style( string $block_name, array $args )


为特定块引入样式表


如果主题选择了单独加载样式,那么样式表将在渲染时排队,否则在块初始化时排队。


参数说明:


$block_name 块名称,包括命名空间


$args 包括下面字段:


handle 样式表的句柄


src 样式表的源URL


deps 已注册样式表数组处理此样式表依赖于


ver 样式表版本号


media 已为其定义此样式表的媒体


path 样式表的绝对路径,因此它可能被内联


函数源码:


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

	$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_separate_core_block_assets() ) {
		$callback_separate = static function ( $content, $block ) use ( $block_name, $callback ) {
			if ( ! empty( $block['blockName'] ) && $block_name === $block['blockName'] ) {
				return $callback( $content );
			}
			return $content;
		};

		add_filter( 'render_block', $callback_separate, 10, 2 );
		return;
	}

	add_filter( $hook, $callback );

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


使用举例:


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 );
    }
}


发表评论

暂无评论,抢个沙发...

客服 工单