跳转到正文

从 ACF Blocks迁移

如果你一直使用 ACF(Advanced Custom Fields)构建自定义 WordPress区块,那么迁移到 Blockstudio很简单。两者概念相似:定义字段、编写模板,区块便会显示在编辑器中。区别在于,Blockstudio会自动发现区块文件夹,在 block.json中使用自己的架构声明字段,并将所有字段值作为一个 $a数组传给每个模板。

本指南将逐步介绍迁移过程,并并排比较 ACF和 Blockstudio的模式。

核心区别

从 ACF 6.0 起,ACF区块就是一个 block.json,其中包含命名渲染模板的 acf键;每个区块文件夹都通过独立的 register_block_type()调用注册。字段来自附加到区块的字段组,附加方式可以是 Block 位置规则(在管理后台创建、通过 Local JSON同步,或使用 acf_add_local_field_group()注册),也可以从 ACF PRO 6.8.1起,直接使用同一 block.json中的内联 acf.fields数组。Blockstudio以基于文件的自动发现取代注册调用:创建一个包含 block.json和 index.php的文件夹,区块就会自动注册。

ACF:

JSON
{
  "name": "acf/hero",
  "title": "Hero",
  "acf": {
    "renderTemplate": "template.php"
  }
}
PHP
add_action( 'init', function () {
  register_block_type( __DIR__ . '/blocks/hero' );
} );
PHP
acf_add_local_field_group([
  'key'      => 'group_hero',
  'title'    => 'Hero Fields',
  'fields'   => [
    ['key' => 'field_title', 'name' => 'title', 'type' => 'text', 'label' => 'Title'],
    ['key' => 'field_image', 'name' => 'image', 'type' => 'image', 'label' => 'Background', 'return_format' => 'array'],
  ],
  'location' => [[['param' => 'block', 'operator' => '==', 'value' => 'acf/hero']]],
]);
PHP
<?php
$title = get_field('title');
$image = get_field('image');
?>
<div class="hero" <?php if ($image) : ?>style="background-image: url(<?php echo esc_url($image['url']); ?>)"<?php endif; ?>>
  <h1><?php echo esc_html($title); ?></h1>
</div>

Blockstudio:

JSON
{
  "name": "my-theme/hero",
  "title": "Hero",
  "blockstudio": {
    "attributes": [
      { "id": "title", "type": "text", "label": "Title" },
      { "id": "image", "type": "files", "label": "Background", "multiple": false }
    ]
  }
}
PHP
<div useBlockProps class="hero" <?php if ($a['image']) : ?>style="background-image: url(<?php echo esc_url($a['image']['url']); ?>)"<?php endif; ?>>
  <h1><?php echo esc_html($a['title']); ?></h1>
</div>

无需注册调用,也无需渲染回调:文件夹结构本身就是注册信息,字段与模板一起存放在 block.json中。模板读取 $a,而不是调用 get_field()。

区块注册

ACF

当前 ACF区块通过带有 acf键的 block.json注册(renderTemplate或 renderCallback,以及 blockVersion等选项),通常在 functions.php中的 init或插件文件里,为每个区块文件夹显式调用一次 register_block_type()来加载。旧区块可能仍使用 acf_register_block_type();ACF已将其列为弃用,自 ACF 6.0 起生效。它仍可继续使用,因此迁移这些区块时采用相同方式即可。

Blockstudio

在主题的 blockstudio/目录(或你更喜欢的 blocks/目录)中创建文件夹。添加包含标准 WordPress区块元数据和 blockstudio键的 block.json。就这么简单。

代码
theme/
└── blockstudio/
    └── hero/
        ├── block.json
        └── index.php

block.json使用标准 WordPress block.json格式,通过 blockstudio键指定字段和配置:

JSON
{
  "name": "my-theme/hero",
  "title": "Hero",
  "category": "theme",
  "icon": "cover-image",
  "description": "Full-width hero section with background image.",
  "blockstudio": {
    "attributes": []
  }
}

访问字段值

这是迁移过程中最常见的改动。

ACF Blockstudio
get_field('title') $a['title']
get_field('title', $post_id) $a['title'](始终可用)
the_field('title') <?php echo $a['title']; ?>
have_rows('items') / the_row() foreach ($a['items'] as $item)
get_sub_field('name') $item['name']

$a变量是 $attributes的简写,包含当前区块的所有字段值。无论在编辑器还是前端,它在模板中始终可用。

模板变量

Blockstudio会在每个模板中提供多个变量:

变量 简写 说明
$attributes $a 所有字段值
$block $b 区块元数据(名称、标题、目录、URL、文章 ID)
$context $c 父区块上下文
$content InnerBlocks 内容
$post_id 当前文章 ID(在编辑器和前端均可用;在 Twig中为 post_id或 postId)

字段类型映射

大多数 ACF字段类型在 Blockstudio中都有直接对应项。JSON语法虽然不同,但概念可以直接映射。

文本和内容字段

ACF:

PHP
['name' => 'title', 'type' => 'text', 'label' => 'Title', 'default_value' => 'Hello']
['name' => 'bio', 'type' => 'textarea', 'label' => 'Bio', 'rows' => 4]
['name' => 'content', 'type' => 'wysiwyg', 'label' => 'Content']

Blockstudio:

JSON
{ "id": "title", "type": "text", "label": "Title", "default": "Hello" }
{ "id": "bio", "type": "textarea", "label": "Bio", "rows": 4 }
{ "id": "content", "type": "wysiwyg", "label": "Content" }

若要在区块编辑器中编辑文本(而不只是使用文本输入框),请使用 <RichText />组件搭配 richtext类型:

JSON
{ "id": "heading", "type": "richtext" }
PHP
<RichText attribute="heading" tag="h1" placeholder="Enter heading" />

图像和文件字段

ACF的 image和 file字段对应 Blockstudio的 files类型:

ACF:

PHP
['name' => 'photo', 'type' => 'image', 'return_format' => 'array']
['name' => 'gallery', 'type' => 'gallery', 'return_format' => 'array']
['name' => 'document', 'type' => 'file', 'return_format' => 'array']

Blockstudio:

JSON
{ "id": "photo", "type": "files", "label": "Photo", "multiple": false }
{ "id": "gallery", "type": "files", "label": "Gallery", "multiple": true }
{ "id": "document", "type": "files", "label": "Document", "multiple": false, "allowedTypes": ["application/pdf"] }

返回对象的结构相似:

PHP
// ACF
$image = get_field('photo');
echo $image['url'];
echo $image['alt'];

// Blockstudio
echo $a['photo']['url'];
echo $a['photo']['alt'];

可用属性:ID、title、alt、caption、description、href、url、sizes。尺寸位于 sizes 中,例如 $a['photo']['sizes']['full-width']。

选择、单选和复选框

ACF:

PHP
[
  'name' => 'color',
  'type' => 'select',
  'choices' => ['red' => 'Red', 'blue' => 'Blue'],
  'return_format' => 'value',
]

Blockstudio:

JSON
{
  "id": "color",
  "type": "select",
  "label": "Color",
  "options": [
    { "value": "red", "label": "Red" },
    { "value": "blue", "label": "Blue" }
  ]
}

使用 "returnFormat": "both"同时获取值和标签:

PHP
echo $a['color']['value'];  // "red"
echo $a['color']['label'];  // "Red"

同样的模式也适用于 radio和 checkbox类型。

开关和真/假值

ACF:

PHP
['name' => 'show_cta', 'type' => 'true_false', 'label' => 'Show CTA']

Blockstudio:

JSON
{ "id": "showCta", "type": "toggle", "label": "Show CTA" }

ACF:

PHP
['name' => 'cta', 'type' => 'link', 'return_format' => 'array']

// Template
$link = get_field('cta');
echo $link['url'];
echo $link['title'];
echo $link['target'];

Blockstudio:

JSON
{ "id": "cta", "type": "link", "label": "CTA", "opensInNewTab": true }
PHP
echo $a['cta']['url'];
echo $a['cta']['title'];
echo $a['cta']['target'];

颜色和渐变

ACF:

PHP
['name' => 'bgColor', 'type' => 'color_picker', 'label' => 'Background']

Blockstudio:

JSON
{ "id": "bgColor", "type": "color", "label": "Background" }
{ "id": "bgGradient", "type": "gradient", "label": "Background Gradient" }

color类型集成了 WordPress调色板。gradient类型提供渐变选择器。

数字、范围和日期

ACF:

PHP
['name' => 'count', 'type' => 'number', 'min' => 1, 'max' => 10]
['name' => 'opacity', 'type' => 'range', 'min' => 0, 'max' => 100, 'step' => 5]
['name' => 'eventDate', 'type' => 'date_picker']

Blockstudio:

JSON
{ "id": "count", "type": "number", "label": "Count", "min": 1, "max": 10 }
{ "id": "opacity", "type": "range", "label": "Opacity", "min": 0, "max": 100, "step": 5 }
{ "id": "eventDate", "type": "date", "label": "Event Date" }

重复器

ACF的重复器字段直接对应 Blockstudio的 repeater类型。ACF模板通常使用 have_rows() / the_row() / get_sub_field()循环(重复器上的 get_field()也会返回行数组);Blockstudio只有普通的 PHP数组,且已是 $a格式。

ACF:

PHP
['name' => 'features', 'type' => 'repeater', 'sub_fields' => [
  ['name' => 'title', 'type' => 'text'],
  ['name' => 'description', 'type' => 'textarea'],
]]

// Template
if (have_rows('features')) :
  while (have_rows('features')) : the_row();
    echo get_sub_field('title');
    echo get_sub_field('description');
  endwhile;
endif;

Blockstudio:

JSON
{
  "id": "features",
  "type": "repeater",
  "label": "Features",
  "min": 1,
  "max": 10,
  "attributes": [
    { "id": "title", "type": "text", "label": "Title" },
    { "id": "description", "type": "textarea", "label": "Description" }
  ]
}
PHP
<?php foreach ($a['features'] as $feature) : ?>
  <h3><?php echo esc_html($feature['title']); ?></h3>
  <p><?php echo esc_html($feature['description']); ?></p>
<?php endforeach; ?>

Blockstudio重复器最多支持 3 层嵌套(即重复器中再嵌套重复器)。

分组

ACF的分组字段对应 Blockstudio的 group类型。分组内的字段 ID 会加上分组 ID 前缀。

ACF:

PHP
['name' => 'author', 'type' => 'group', 'sub_fields' => [
  ['name' => 'name', 'type' => 'text'],
  ['name' => 'role', 'type' => 'text'],
]]

// Template
$author = get_field('author');
echo $author['name'];
echo $author['role'];

Blockstudio:

JSON
{
  "id": "author",
  "type": "group",
  "title": "Author",
  "attributes": [
    { "id": "name", "type": "text", "label": "Name" },
    { "id": "role", "type": "text", "label": "Role" }
  ]
}
PHP
<?php $author = bs_get_group($a, 'author'); ?>
<p><?php echo esc_html($author['name']); ?></p>
<p><?php echo esc_html($author['role']); ?></p>

bs_get_group()辅助函数会从字段 ID 中移除分组前缀,方便直接访问字段。不使用它时,访问字段的方式是 $a['author_name']和 $a['author_role']。

条件逻辑

ACF和 Blockstudio都支持条件逻辑,可根据其他字段值显示或隐藏字段。

ACF:

PHP
['name' => 'showSubtitle', 'type' => 'true_false'],
[
  'name' => 'subtitle',
  'type' => 'text',
  'conditional_logic' => [[['field' => 'field_showSubtitle', 'operator' => '==', 'value' => '1']]]
]

Blockstudio:

JSON
{ "id": "showSubtitle", "type": "toggle", "label": "Show Subtitle" },
{
  "id": "subtitle",
  "type": "text",
  "label": "Subtitle",
  "conditions": [[{ "id": "showSubtitle", "operator": "==", "value": true }]]
}

Blockstudio条件直接引用字段 ID(而非字段键)。可用运算符:==、!=、includes、!includes、empty、!empty、<、>、<=、>=。

Blockstudio还支持根据文章类型、文章 ID、用户角色和用户 ID 设置全局条件:

JSON
{
  "conditions": [[{ "type": "postType", "operator": "==", "value": "page" }]]
}

InnerBlocks

ACF和 Blockstudio都支持 InnerBlocks,可在自定义区块中嵌套其他区块,并使用相同的 <InnerBlocks />标签以及相同的 allowedBlocks、template和 templateLock属性,因此模板中的这部分通常无需改动即可迁移。

Blockstudio:

PHP
<div useBlockProps class="my-wrapper">
  <InnerBlocks
    allowedBlocks='<?php echo esc_attr(wp_json_encode(["core/heading", "core/paragraph", "core/image"])); ?>'
    template='<?php echo esc_attr(wp_json_encode([
      ["core/heading", ["placeholder" => "Section title"]],
      ["core/paragraph", ["placeholder" => "Section content"]]
    ])); ?>'
    templateLock="insert"
  />
</div>

在编辑器中,<InnerBlocks />标签会替换为 React组件;在前端则会替换为渲染后的区块内容。

文章元数据存储

默认情况下,ACF Blocks 和 Blockstudio 都会将字段值作为区块属性存储在文章内容中,而不是文章元数据中。这意味着除非选择启用元数据存储,否则无法使用 WP_Query 查询字段值。

ACF 在 ACF PRO 6.3 中通过 usePostMeta: true 添加了区块文章元数据存储的可选启用功能,每页适用于一个顶层区块。Blockstudio 则可按字段选择启用,通过 storage 属性实现:

JSON
{
  "id": "featured",
  "type": "toggle",
  "label": "Featured",
  "storage": {
    "type": "postMeta",
    "postMetaKey": "is_featured"
  }
}

元数据键会通过 show_in_rest 自动注册。可通过 get_post_meta($post_id, 'is_featured', true) 在任意位置访问它。

对于站点范围的值(如 ACF 选项页面),请使用选项存储:

JSON
{
  "storage": {
    "type": "option",
    "optionKey": "site_company_name"
  }
}

扩展现有区块

ACF 的区块位置规则仅将字段组附加到 ACF 区块;它不会向核心区块或第三方区块添加字段。要扩展 Heading、Paragraph、Image 和 Button 等核心区块,ACF 提供的方式是 WordPress Block BindingsAPI,可将现有区块属性连接到 ACF 字段值。Blockstudio 可通过扩展文件向任何已注册区块添加新字段和控件。

在你的 blockstudio 目录中创建一个扩展文件:

JSON
{
  "name": "core/heading",
  "blockstudio": {
    "extend": true,
    "attributes": [
      {
        "id": "accentColor",
        "type": "color",
        "label": "Accent Color",
        "set": [{ "attribute": "style", "value": "color: {attributes.accentColor}" }]
      }
    ]
  }
}

set 属性会自动将字段值应用到区块的 HTML。使用通配符可一次扩展多个区块:"name": "core/*"。

迁移清单

  1. 创建区块文件夹:在 theme/blockstudio/{block-name}/ 中使用 block.json 和 index.php 创建文件夹。
  2. 移动字段定义:将区块字段组中的字段定义(本地 JSON、acf_add_local_field_group() 或内联 acf.fields 数组)移动到 block.json 中的 blockstudio.attributes 数组。将 name 改为 id,移除 key,并按需调整类型名称。
  3. 更新模板访问方式:从 get_field('name') 改为 $a['name']。将 have_rows() 循环替换为 foreach ($a['repeater'] as $item)。
  4. 将 get_sub_field() 替换为直接数组访问:$item['fieldId']。
  5. 在模板最外层元素中添加 useBlockProps,以便与编辑器正确集成。
  6. 移动条件逻辑:将 ACF 的 conditional_logic 移至 Blockstudio 的 conditions,并使用字段 ID 而非字段键进行引用。
  7. 添加存储:为此前通过 get_post_meta() 查询或在 WP_Query 中使用的字段添加存储。
  8. 移除 ACF 注册代码:删除已迁移区块的 register_block_type() 调用和 acf 键(或其 acf_register_block_type() 调用),并移除对应字段组,无论它们位于本地 JSON、acf_add_local_field_group()、内联 acf.fields 数组还是管理界面中。
  9. 在编辑器中测试,确认字段显示正确,然后检查前端输出。