如何为块添加 theme.json 样式变量,使颜色与主题设计令牌保持一致?

解读

国内一线 WordPress 团队已将「设计令牌」写进主题开发规范:所有颜色、字号、间距必须走 theme.json,禁止在 CSS 里硬编码。面试官问此题,想看三点:

  1. 你是否理解 theme.json 的顶层 settings.color.palette 与 styles.blocks.*.color 的映射关系;
  2. 能否把设计稿中的色号抽象成语义化令牌,并同步到 Gutenberg 调色板;
  3. 是否知道让自定义块自动继承这些令牌,而不必再写死颜色。
    答不到「令牌同步」与「块级继承」两层,基本会被判为初级。

知识点

  • theme.json 结构层级:settings、styles、custom、templateParts、version
  • settings.color.palette 数组:name、slug、color 三字段,slug 即设计令牌
  • styles.blocks.{blockName}.color 对象:background、text、gradient 可引用 var(--wp--preset--color--{slug})
  • CSS 自定义属性注入:WordPress 在 body 上输出 --wp--preset--color--{slug} 与 --wp--custom--{customToken}
  • 块级支持声明:block.json 的 supports.color.__experimentalDefaultControls 与 color.defaultPalette
  • 令命名规范:国内大厂惯用「primary-60」「primary-40」等 HCT 分级,slug 保持小写+连字符
  • 多主题切换:通过 switch_theme 钩子重新生成 palette,保证令牌不硬编码在块里
  • 性能与安全:禁用默认调色板需设置 defaultPalette 为 false,避免多余 CSS 输出

答案

  1. 在主题根目录新建或编辑 theme.json,在 settings.color.palette 中定义设计令牌:
{
  "version": 2,
  "settings": {
    "color": {
      "defaultPalette": false,
      "palette": [
        { "name": "主色-60", "slug": "primary-60", "color": "#0052cc" },
        { "name": "功能-成功", "slug": "func-success", "color": "#00b578" }
      ]
    }
  }
}
  1. 在 styles.blocks 节点为指定块引用令牌,确保前端与编辑器一致:
"styles": {
  "blocks": {
    "create-block/alert": {
      "color": {
        "background": "var(--wp--preset--color--primary-60)",
        "text": "var(--wp--preset--color--func-success)"
      }
    }
  }
}
  1. 在自定义块的 block.json 中声明颜色支持,让编辑器自动呈现主题调色板:
"supports": {
  "color": {
    "background": true,
    "text": true,
    "__experimentalDefaultControls": {
      "background": true,
      "text": true
    }
  }
}
  1. 如需额外自定义令牌,可在 theme.json.custom 区写入:
"custom": {
  "line-height": {
    "base": "1.6",
    "heading": "1.3"
  }
}

并在块样式里用 var(--wp--custom--line-height--base) 调用。
5. 最后执行 wp-cli theme validate-theme-json 检查语法,确认无警告后提交仓库。至此,块的颜色已与主题设计令牌保持单源真理,设计师改色号只需更新 theme.json,无需触碰代码。

拓展思考

  • 动态令牌:若客户后台需可视化调色,可通过 wp_theme_json_data_user 过滤器把用户选择写入数据库,实现「子主题级」令牌覆盖,而父主题仍保留默认 palette。
  • 暗色模式:利用 prefers-color-scheme 与 theme.json.styles.elements.body.color,在同一套 slug 下切换色号,保证块自动适配。
  • 组件库协同:将 theme.json 的 palette 同步到 Figma Tokens 或 Tailwind 配置,实现「设计-代码」双向同步,减少 UI 走查成本。
  • 性能极限:对于大型站点,可把 palette 拆分为 theme.json.d/palette/*.json,在 functions.php 用 wp_theme_json_data_theme 合并,降低单个文件体积,兼顾缓存与可维护性。