跳转到正文

构建自定义字段类型

有些值不止一个原始值。价格由金额和货币组成。使用内置字段时,你需要并排设置数字字段和选择字段;每个显示价格的区块都会重复这两个字段、标签,以及确保它们保持关联的逻辑。在文章元数据中,这会变成两个键;在重复器中,则会变成两个并行列表。

自定义字段类型可将这两个值合并为一个字段。你只需在 PHP 和 JavaScript 中注册一次类型,例如 acme/price,之后就能像使用原生字段一样在任何 block.json 中使用它:顶层、组和重复器内部、文章元数据或选项存储中,以及 PHP、Twig 和 Blade 模板中。Blockstudio 会根据注册信息生成 WordPress 属性和存储 REST 架构。

这与自定义字段不同。 custom/{name} 引用会复用一组现有字段。自定义字段类型则会添加一个具有自身值结构的新控件。

本指南将从头到尾构建 acme/price:包括 PHP 注册、编辑器控件、在顶层和重复器中使用它的定价区块、具有严格 REST 架构的文章元数据存储,以及渲染后的输出。

在 PHP 中注册类型

PHP 部分会声明属性类型、默认值、提供控件的编辑器脚本,以及如何在区块之外存储该值:

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

	bs_register_field_type( 'acme/price', array(
		'attribute'     => 'object',
		'default'       => array(),
		'editor_script' => 'acme-field-price',
		'storage'       => array(
			'type'        => 'object',
			'rest_schema' => array(
				'type'                 => 'object',
				'properties'           => array(
					'amount'   => array( 'type' => 'number', 'minimum' => 0 ),
					'currency' => array( 'type' => 'string', 'pattern' => '^[A-Z]{3}$' ),
				),
				'additionalProperties' => false,
			),
		),
	) );
} );

attribute 是 WordPress 属性类型,此处为 object。storage.type 是字段存储在文章元数据或选项中时所用的值类型,storage.rest_schema 是用于验证 REST 写入的架构 WordPress。如果没有 rest_schema,对象值会得到一个允许任意属性的宽松架构。

在默认优先级下,于 init 上注册。Blockstudio 会在 init 上较晚发现区块;届时尚未注册的类型不会包含在生成的区块属性中。

bs_register_field_type() 成功时返回 true,名称或定义无效时返回 false。名称必须为小写、带命名空间并使用短横线命名法;以下两个命名空间已被保留:

名称 结果
acme/price true
Acme/Price false,不是小写
custom/price false,保留用于可复用字段组
blockstudio/price false,保留给 Blockstudio 核心

bs_unregister_field_type() 可以移除已有注册,而 blockstudio/field_types 过滤器接受按名称作为键的相同定义数组。

构建编辑器控件

上面注册的脚本提供 React 组件。它使用编辑器中已加载的 WordPress 组件,因此无需构建步骤:

JavaScript
const { createElement: el } = wp.element;
const { Flex, FlexBlock, FlexItem, SelectControl, TextControl } = wp.components;

window.blockstudio.registerFieldType('acme/price', {
  component(props) {
    const value =
      props.value && typeof props.value === 'object' && !Array.isArray(props.value)
        ? props.value
        : {};
    const currencies = props.currencies || ['EUR'];

    return el(
      Flex,
      { align: 'flex-end' },
      el(
        FlexBlock,
        {},
        el(TextControl, {
          label: props.label,
          type: 'number',
          min: 0,
          step: 0.01,
          disabled: props.disabled,
          value: value.amount ?? '',
          onChange(next) {
            props.onChange({ ...value, amount: next === '' ? 0 : Number(next) });
          },
        }),
      ),
      el(
        FlexItem,
        {},
        el(SelectControl, {
          label: 'Currency',
          hideLabelFromVision: true,
          disabled: props.disabled,
          value: value.currency || currencies[0],
          options: currencies.map((code) => ({ label: code, value: code })),
          onChange(next) {
            props.onChange({ ...value, currency: next });
          },
        }),
      ),
    );
  },
});

该组件会接收字段定义中的每个属性,因此你放入 block.json 的 currencies 键会作为 props.currencies 传入。它还会接收稳定的属性:value、onChange、field、defaultValue、attributes、block、clientId、disabled 和 inRepeater;当组件在重复器行内渲染时,还会接收 repeaterId。onChange 会原样存储给定值。自定义值不会经过原生 select、radio、color 和 gradient 字段所使用的选项规范化处理。

像前几行那样,对非对象值进行防护。区块可能是在字段出现之前保存的,也可能具有不同的结构;这类区块仍应能在编辑器中打开。

只有在注册了使用 acme/price 的区块时,Blockstudio 才会仅在区块编辑器中加载 acme-field-price。如果脚本未能注册控件,编辑器会保留已保存的值,并在字段位置显示不可编辑的通知;前端仍会渲染该值。

在区块中使用

定价区块会两次使用这种类型:一次用于可在区块外查询的起始价格,另一次用于重复器中每一行的价格层级:

JSON
{
  "$schema": "https://blockstudio.dev/schema/block",
  "apiVersion": 3,
  "name": "acme/pricing",
  "title": "Pricing",
  "blockstudio": {
    "attributes": [
      {
        "id": "price",
        "type": "acme/price",
        "label": "Starting price",
        "currencies": ["EUR", "USD"],
        "default": { "amount": 19, "currency": "EUR" },
        "storage": {
          "type": "postMeta",
          "postMetaKey": "acme_price"
        }
      },
      {
        "id": "tiers",
        "type": "repeater",
        "label": "Tiers",
        "min": 0,
        "max": 4,
        "attributes": [
          { "id": "name", "type": "text", "label": "Name", "default": "" },
          {
            "id": "price",
            "type": "acme/price",
            "label": "Price",
            "currencies": ["EUR", "USD"],
            "default": { "amount": 0, "currency": "EUR" },
            "storage": {
              "type": "postMeta",
              "postMetaKey": "acme_tier_prices"
            }
          }
        ]
      }
    ]
  }
}

字段级的 default 优先于注册表默认值。Blockstudio 会根据注册信息将两个字段都转换为 WordPress 属性。注册的区块类型包含:

JSON
{
  "price": {
    "blockstudio": true,
    "type": "object",
    "field": "acme/price",
    "id": "price",
    "default": { "amount": 19, "currency": "EUR" },
    "storage": { "type": "postMeta", "postMetaKey": "acme_price" }
  },
  "tiers": {
    "blockstudio": true,
    "type": "array",
    "field": "repeater",
    "id": "tiers",
    "attributes": [
      { "blockstudio": true, "type": "string", "field": "text", "default": "", "id": "name" },
      {
        "blockstudio": true,
        "type": "object",
        "field": "acme/price",
        "id": "price",
        "default": { "amount": 0, "currency": "EUR" },
        "storage": { "type": "postMeta", "postMetaKey": "acme_tier_prices" }
      }
    ]
  }
}

渲染值

在模板中,该值是一个普通数组。使用之前先缩小其类型范围,因为存储值的可信度取决于最后一次写入它的操作:

PHP
<?php
/** @var array{price: mixed, tiers: array<int, array{name: string, price: mixed}>} $a */
$format = static function ( mixed $price ): string {
	if ( ! is_array( $price ) ) {
		return '';
	}
	$amount   = is_numeric( $price['amount'] ?? null ) ? (float) $price['amount'] : 0.0;
	$currency = is_string( $price['currency'] ?? null ) ? $price['currency'] : '';

	return number_format_i18n( $amount, 2 ) . ' ' . $currency;
};
?>
<section useBlockProps class="acme-pricing">
  <p>From <?php echo esc_html( $format( $a['price'] ) ); ?></p>
  <?php foreach ( $a['tiers'] ?: array() as $tier ) : ?>
    <div class="acme-tier">
      <h3><?php echo esc_html( $tier['name'] ); ?></h3>
      <p><?php echo esc_html( $format( $tier['price'] ?? null ) ); ?></p>
    </div>
  <?php endforeach; ?>
</section>

?: array() 很重要。没有行的重复器在模板中会呈现为 false,而不是空数组;直接对它使用 foreach 会触发 PHP 警告。下面的 @var 行将在静态分析部分说明。

使用起始价格和两个价格层级渲染区块:

PHP
echo bs_block( array(
	'name' => 'acme/pricing',
	'data' => array(
		'price' => array( 'amount' => 19, 'currency' => 'EUR' ),
		'tiers' => array(
			array( 'name' => 'Starter', 'price' => array( 'amount' => 19, 'currency' => 'EUR' ) ),
			array( 'name' => 'Team', 'price' => array( 'amount' => 49, 'currency' => 'EUR' ) ),
		),
	),
) );
HTML
<!--blockstudio/acme/pricing--><section class="acme-pricing wp-block-acme-pricing">
  <p>From 19.00 EUR</p>
      <div class="acme-tier">
      <h3>Starter</h3>
      <p>19.00 EUR</p>
    </div>
      <div class="acme-tier">
      <h3>Team</h3>
      <p>49.00 EUR</p>
    </div>
  </section>

完全没有数据时,字段默认值会生效,区块会渲染 From 19.00 EUR,且不含任何价格层级。Twig 和 Blade 读取的值与 a.price.amount 和 $a['price']['amount'] 相同,扩展 模板也可以通过 {attributes.price.amount} 访问它。

存储和 REST 架构

两个字段都声明使用 postMeta 存储,因此 Blockstudio 在构建区块时会注册两个元数据键。顶层字段会原样使用已注册的存储架构:

JSON
{
  "type": "object",
  "single": true,
  "show_in_rest": {
    "schema": {
      "type": "object",
      "properties": {
        "amount": { "type": "number", "minimum": 0 },
        "currency": { "type": "string", "pattern": "^[A-Z]{3}$" }
      },
      "additionalProperties": false
    }
  }
}

重复器中的字段会为每行存储一个值,因此其元数据键由数组承载,同一架构会成为各项的架构:

JSON
{
  "type": "array",
  "single": true,
  "show_in_rest": {
    "schema": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "amount": { "type": "number", "minimum": 0 },
          "currency": { "type": "string", "pattern": "^[A-Z]{3}$" }
        },
        "additionalProperties": false
      }
    }
  }
}

保存包含该区块的文章时,会同步两个键。使用上文的两个价格层级时,get_post_meta( $id, 'acme_price', true ) 返回 {"amount":19,"currency":"EUR"},而 acme_tier_prices 返回各行价格组成的列表:

JSON
[
  { "amount": 19, "currency": "EUR" },
  { "amount": 49, "currency": "EUR" }
]

两个键都会出现在文章的 REST 响应中,位于 meta 下;REST 写入会根据架构进行验证。小写货币代码的写入会被拒绝:

JSON
{
  "code": "rest_invalid_pattern",
  "message": "meta.acme_price[currency] does not match pattern ^[A-Z]{3}$.",
  "data": { "status": 400 }
}

元数据只是副本。文章内容中的区块属性仍是数据源,每次保存都会再次将它们同步到已配置的键,因此直接写入元数据的值会在下次保存文章时被替换。选项存储通过 register_setting() 也以相同方式工作。自定义字段类型(包括重复器中的数组存储)从 Blockstudio 7.5.0 起可用。

静态分析

PHPStan扩展 了解内置字段类型,但不了解项目在运行时注册的类型。对于使用 acme/price 的区块,它会报告字段类型未知,并将其值类型推断为 mixed:

Text
  2      block.json field "price" has unknown type "acme/price" in
         blockstudio/pricing/block.json
         🪪  blockstudio.blockJson.type

在项目配置中忽略针对自定义类型的这条诊断,同时保留模板中的类型缩小;PHPStan 需要这样才能接受级别为 max 的 mixed 值:

Neon
parameters:
    level: max
    ignoreErrors:
        -
            identifier: blockstudio.blockJson.type
            message: '#unknown type "acme/price"#'

完成上述配置和模板后,分析即可通过。在 7.6 中,模板还需要 @var 行,并在自定义字段所在位置使用 mixed;Blockstudio 7.7 会自行推断此结构,因此可以移除该行。有关如何运行分析,请参阅使用 PHPStan 检查模板⟧。

后续步骤