函数文档

get_block_editor_theme_styles()

💡 云策文档标注

概述

get_block_editor_theme_styles() 函数用于生成一个主题样式数组,以便加载到块编辑器中。它检查当前主题是否支持 'editor-styles',并处理本地或远程样式文件。

关键要点

  • 函数返回一个数组,包含主题样式数据,用于块编辑器设置。
  • 通过全局变量 $editor_styles 和 current_theme_supports('editor-styles') 条件判断是否处理样式。
  • 支持处理远程 URL 样式(使用 wp_remote_get 获取)和本地文件样式(使用 get_theme_file_path 和 file_get_contents 读取)。
  • 每个样式项包含 'css'、'__unstableType' 和 'isGlobalStyles' 等键,本地文件还包含 'baseURL'。

代码示例

function get_block_editor_theme_styles() {
	global $editor_styles;

	$styles = array();

	if ( $editor_styles && current_theme_supports( 'editor-styles' ) ) {
		foreach ( $editor_styles as $style ) {
			if ( preg_match( '~^(https?:)?//~', $style ) ) {
				$response = wp_remote_get( $style );
				if ( ! is_wp_error( $response ) ) {
					$styles[] = array(
						'css'            => wp_remote_retrieve_body( $response ),
						'__unstableType' => 'theme',
						'isGlobalStyles' => false,
					);
				}
			} else {
				$file = get_theme_file_path( $style );
				if ( is_file( $file ) ) {
					$styles[] = array(
						'css'            => file_get_contents( $file ),
						'baseURL'        => get_theme_file_uri( $style ),
						'__unstableType' => 'theme',
						'isGlobalStyles' => false,
					);
				}
			}
		}
	}

	return $styles;
}

注意事项

  • 函数自 WordPress 5.8.0 版本引入,用于块编辑器主题样式集成。
  • 依赖多个 WordPress 核心函数,如 get_theme_file_path、wp_remote_get 等,确保环境支持。
  • 样式数组中的 '__unstableType' 和 'isGlobalStyles' 键可能在未来版本中变化,使用时需注意兼容性。

📄 原文内容

Creates an array of theme styles to load into the block editor.

Return

array An array of theme styles for the block editor.

Source

function get_block_editor_theme_styles() {
	global $editor_styles;

	$styles = array();

	if ( $editor_styles && current_theme_supports( 'editor-styles' ) ) {
		foreach ( $editor_styles as $style ) {
			if ( preg_match( '~^(https?:)?//~', $style ) ) {
				$response = wp_remote_get( $style );
				if ( ! is_wp_error( $response ) ) {
					$styles[] = array(
						'css'            => wp_remote_retrieve_body( $response ),
						'__unstableType' => 'theme',
						'isGlobalStyles' => false,
					);
				}
			} else {
				$file = get_theme_file_path( $style );
				if ( is_file( $file ) ) {
					$styles[] = array(
						'css'            => file_get_contents( $file ),
						'baseURL'        => get_theme_file_uri( $style ),
						'__unstableType' => 'theme',
						'isGlobalStyles' => false,
					);
				}
			}
		}
	}

	return $styles;
}

Changelog

Version Description
5.8.0 Introduced.