跳转到正文

自定义字段类型

自定义字段类型允许主题或插件添加新的 Blockstudio 字段控件。 它们与自定义字段不同:

  • custom/{name} 引用一组可重复使用的现有字段。
  • namespace/type-name 使用已注册的字段类型,该类型具有自己的编辑器 控件和值结构。

Blockstudio提供注册系统。控件由你的主题或插件提供。

何时使用

当项目需要一个专用的编辑控件,并且希望它在各处都像原生 Blockstudio 字段一样运行时,请使用自定义字段类型:

  • 区块属性
  • 可重复使用的 custom/{name} 字段组
  • 组、选项卡和 Repeater
  • PHP、Twig 和 Blade 模板
  • 文章元数据和选项存储
  • 扩展模板,例如 {attributes.margin.top}

例如,间距控件可以存储一个对象,而不是四个单独的 文本字段:

JSON
{
  "blockstudio": {
    "attributes": [
      {
        "id": "margin",
        "type": "acme/dimensions",
        "label": "Margin",
        "sides": ["top", "right", "bottom", "left"],
        "default": {
          "top": "sm",
          "right": "md",
          "bottom": "sm",
          "left": "md"
        }
      }
    ]
  }
}

命名

自定义字段类型名称必须使用小写、带命名空间的 kebab-case:

Text
namespace/type-name

有效示例:

  • acme/dimensions
  • acme/text-options
  • theme/spacing-token

保留的命名空间:

  • custom/ 保留用于可重复使用的自定义字段组。
  • blockstudio/ 保留用于 Blockstudio 核心。

无效名称会被筛选器 API 忽略,并被辅助函数 API 拒绝。

PHP 注册

在 PHP 中注册字段类型元数据:

PHP
add_action('init', function () {
    wp_register_script(
        'acme-field-dimensions',
        get_stylesheet_directory_uri() . '/fields/dimensions.js',
        ['blockstudio-blocks', 'wp-components', 'wp-element'],
        '1.0.0',
        true
    );

    bs_register_field_type('acme/dimensions', [
        'attribute'     => 'object',
        'default'       => [],
        'editor_script' => 'acme-field-dimensions',
        'storage'       => [
            'type'        => 'object',
            'rest_schema' => [
                'type'                 => 'object',
                'additionalProperties' => ['type' => 'string'],
            ],
        ],
    ]);
});

bs_register_field_type()在注册成功时返回 true,名称或定义无效时返回 false。你可以使用 bs_unregister_field_type() 取消手动注册。

你也可以使用筛选器 API:

PHP
add_filter('blockstudio/field_types', function (array $types): array {
    $types['acme/dimensions'] = [
        'attribute'     => 'object',
        'default'       => [],
        'editor_script' => 'acme-field-dimensions',
    ];

    return $types;
});

定义键

键 类型 说明
attribute string, array, null WordPress 属性类型。使用 string、number、boolean、object、array,或这些类型的数组。
default mixed 字段未定义自身默认值时,在注册表级别使用的默认值。
source string 用于自定义序列化场景的 WordPress 属性来源。
produces_attribute boolean 仅用于显示的控件设为 false。默认值为 true。
editor_script string or array 使用该类型时,在区块编辑器中加入队列的已注册脚本句柄。
editor_style string or array 使用该类型时,在区块编辑器中加入队列的已注册样式句柄。
storage array 用于文章元数据和选项的存储值类型及 REST 架构提示。
supports array 供你自己的控件使用的可选功能标志。
translate boolean 当值是供 WPML 翻译的文本时设为 true。需要 attribute string。

translate值不是布尔值的定义,或translate设为true且attribute不是string的定义,均无效。bs_register_field_type()会返回false,且筛选器API会忽略该定义。

WPML

wp bs wpml config 无法仅凭注册信息判断自定义字段类型的值是否为文本,因此会跳过此类字段,并为每个字段输出一条警告。在字段类型注册信息中,将 translate 设为 true,表示该字段存储的是纯文本字符串,命令就会像处理 text 字段一样声明这些字段。字段仍可通过 "translate": false 选择不参与。请参阅 WPML。

PHP
bs_register_field_type('acme/headline', [
    'attribute' => 'string',
    'translate' => true,
]);

JavaScript 注册

编辑器脚本会注册相应的 React 控件:

JavaScript
const { createElement: el } = wp.element;
const { TextControl } = wp.components;

window.blockstudio.registerFieldType('acme/dimensions', {
  component(props) {
    const value =
      props.value &&
      typeof props.value === 'object' &&
      !Array.isArray(props.value)
        ? props.value
        : {};
    const sides = props.sides || ['top', 'right', 'bottom', 'left'];

    return el(
      'div',
      {},
      sides.map((side) =>
        el(TextControl, {
          key: side,
          label: side,
          value: value[side] || '',
          onChange(nextValue) {
            props.onChange({
              ...value,
              [side]: nextValue,
            });
          },
        }),
      ),
    );
  },
});

注册获接受时,registerFieldType()会返回 true。使用以下代码移除客户端注册:

JavaScript
window.blockstudio.unregisterFieldType('acme/dimensions');

组件会接收字段定义属性,以及以下稳定属性:

属性 描述
type 字段类型名称。
id 字段 ID。
field 来自 block.json 的完整字段定义。
value 当前已保存的值。
defaultValue 字段默认值。
onChange 直接存储新值。
attributes 当前区块属性。
block 当前区块类型定义。
clientId 当前编辑器区块客户端 ID。
inRepeater 字段是否位于 Repeater 行内。
repeaterId 当前 Repeater 路径(如有)。
disabled 字段是否在编辑器中被禁用。

自定义字段类型的值会直接存储,不会经过原生 select、radio、color 或 gradient 选项规范化。

渲染值

对象值可像任何其他 Blockstudio 属性一样使用。

PHP

PHP
<div class="<?php echo esc_attr('mt-' . ($a['margin']['top'] ?? '')); ?>">
  <?php echo esc_html($a['title'] ?? ''); ?>
</div>

Twig

Twig
<div class="mt-{{ a.margin.top }}">
  {{ a.title }}
</div>

Blade

Blade
<div class="mt-{{ $a['margin']['top'] ?? '' }}">
  {{ $a['title'] ?? '' }}
</div>

扩展模板中也支持嵌套对象路径:

JSON
{
  "blockstudio": {
    "extend": "core/group",
    "attributes": [
      {
        "id": "margin",
        "type": "acme/dimensions",
        "set": [
          {
            "attribute": "class",
            "value": "mt-{attributes.margin.top} mb-{attributes.margin.bottom}"
          }
        ]
      }
    ]
  }
}

存储

自定义字段类型与 postMeta 或 option 存储搭配使用时,Blockstudio 会使用已注册的存储值类型和 REST 架构。

JSON
{
  "id": "margin",
  "type": "acme/dimensions",
  "label": "Margin",
  "storage": {
    "type": "postMeta",
    "postMetaKey": "acme_margin"
  }
}

对于 array 和 object 值,请在字段类型注册中定义 storage.rest_schema。Repeater 的后代仍使用基于数组的存储,因为 Repeater 会存储行。

回退行为

如果 PHP 认识该字段类型,但编辑器脚本没有注册匹配的控件,Blockstudio 会保留已保存的值,并在编辑器中显示不可编辑的提示。前端渲染仍会接收已保存的值。

如果字段类型未在 PHP 中注册,Blockstudio 会将其从生成的 WordPress 属性中排除。请在运行区块发现之前注册 PHP 定义,通常是在 init 上、Blockstudio 构建区块之前完成。