如何从WordPress theme.json字符串编译生成对应CSS样式规则?
从WordPress theme.json生成CSS的实现方法
PHP端实现
WordPress核心内置了WP_Theme_JSON类,专门用来解析theme.json并生成对应的CSS样式。直接利用这个类即可完成转换,步骤如下:
- 将theme.json字符串解析为PHP数组
- 实例化
WP_Theme_JSON对象并传入解析后的数据 - 调用类方法生成CSS
代码示例:
// 你的theme.json字符串 $theme_json_str = '{ "version": 2, "settings": { "color": { "palette": [{"slug": "primary", "color": "#ff0000", "name": "Primary"}] } }, "styles": { "body": {"color": "var(--wp--preset--color--primary)"} } }'; // 解析JSON字符串 $theme_json_data = json_decode($theme_json_str, true); if (json_last_error() !== JSON_ERROR_NONE) { die('无效的theme JSON格式'); } // 初始化Theme JSON处理对象 $theme_json = new WP_Theme_JSON($theme_json_data); // 生成前端页面用的完整CSS $frontend_css = $theme_json->get_stylesheet(); // 如果需要编辑器专用样式,调用这个方法 $editor_css = $theme_json->get_editor_stylesheet(); // 输出CSS echo '<style>' . $frontend_css . '</style>';
额外说明:
- 如果需要合并WordPress核心默认的theme.json配置(比如默认的颜色、排版预设),可以用
WP_Theme_JSON_Resolver::get_core_data()获取核心数据,再通过$theme_json->merge()方法合并后生成CSS。 - 该方法依赖WordPress核心环境,需在主题或插件的代码中使用,不能在独立PHP脚本中运行。
JS端实现
如果在前端环境(比如自定义编辑器扩展、前端构建流程)中处理,可以使用WordPress官方的@wordpress/theme-json包中的compile函数,它和WordPress核心的转换逻辑完全一致。
代码示例:
// 引入compile函数(需先安装@wordpress/theme-json包) import { compile } from '@wordpress/theme-json'; // 你的theme.json字符串 const themeJsonStr = `{ "version": 2, "settings": { "typography": { "fontSizes": [{"slug": "large", "size": "2rem", "name": "Large"}] } }, "styles": { "h1": {"fontSize": "var(--wp--preset--font-size--large)"} } }`; // 解析JSON const themeJson = JSON.parse(themeJsonStr); // 编译生成CSS const css = compile(themeJson); // 将CSS插入到页面中 const styleElement = document.createElement('style'); styleElement.textContent = css; document.head.appendChild(styleElement);
额外说明:
- 需通过npm安装依赖:
npm install @wordpress/theme-json compile函数会自动处理theme.json中的变量预设、全局样式、块样式等,生成符合WordPress规范的CSS代码。
内容的提问来源于stack exchange,提问作者Romain Guillaume
相关产品推荐
相关产品推荐

