Pāreja no ACF Blocks
Ja esat veidojis pielāgotus WordPress blokus ar ACF (Advanced Custom Fields), pāreja uz Blockstudio ir vienkārša. Jēdzieni ir līdzīgi: definējat laukus, rakstāt veidni, un bloks parādās redaktorā. Atšķirības ir tādas, ka Blockstudio pats atrod bloku mapes, definē laukus savā shēmā block.json iekšpusē un nodod katrai veidnei lauku vērtības vienā $a masīvā.
Šajā rokasgrāmatā soli pa solim izklāstīta pāreja, salīdzinot ACF un Blockstudio pieejas.
Galvenā atšķirība
Kopš ACF 6.0 ACF bloks ir block.json ar atslēgu acf, kas norāda tā renderēšanas veidni, un katra bloka mape tiek reģistrēta ar atsevišķu register_block_type() izsaukumu. Lauki tiek iegūti no lauku grupas, kas piesaistīta blokam ar Block atrašanās vietas noteikumu (izveidota administrēšanas panelī, sinhronizēta ar Local JSON vai reģistrēta ar acf_add_local_field_group()), vai kopš ACF PRO 6.8.1 — no iekļauta acf.fields masīva tajā pašā block.json. Blockstudio reģistrācijas izsaukumu aizstāj ar automātisku failu noteikšanu: izveidojiet mapi ar block.json un index.php, un bloks tiek reģistrēts automātiski.
ACF:
{
"name": "acf/hero",
"title": "Hero",
"acf": {
"renderTemplate": "template.php"
}
}
add_action( 'init', function () {
register_block_type( __DIR__ . '/blocks/hero' );
} );
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
$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:
{
"name": "my-theme/hero",
"title": "Hero",
"blockstudio": {
"attributes": [
{ "id": "title", "type": "text", "label": "Title" },
{ "id": "image", "type": "files", "label": "Background", "multiple": false }
]
}
}
<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>
Reģistrācijas izsaukums un renderēšanas atzvanes funkcija nav vajadzīga: reģistrāciju nosaka mapju struktūra, un lauki atrodas block.json līdzās veidnei. Veidne nolasa $a, nevis izsauc get_field().
Bloku reģistrēšana
ACF
Pašreizējie ACF bloki tiek reģistrēti no block.json ar atslēgu acf (renderTemplate vai renderCallback, kā arī tādām opcijām kā blockVersion), katrai bloka mapei ielādējot atsevišķu register_block_type() izsaukumu, parasti failā init mapē functions.php vai spraudņa failā. Vecāki bloki joprojām var izmantot acf_register_block_type(). ACF kopš ACF 6.0 šo funkciju dokumentē kā novecojušu, taču tā joprojām darbojas, tāpēc migrējiet arī šos blokus tāpat.
Blockstudio
Izveidojiet mapi savas tēmas direktorijā blockstudio/ (vai blocks/, ja tā ērtāk). Pievienojiet block.json ar standarta WordPress bloka metadatiem un atslēgu blockstudio. Tas arī viss.
theme/
└── blockstudio/
└── hero/
├── block.json
└── index.php
block.json izmanto standarta WordPress block.json formātu ar atslēgu blockstudio laukiem un konfigurācijai:
{
"name": "my-theme/hero",
"title": "Hero",
"category": "theme",
"icon": "cover-image",
"description": "Full-width hero section with background image.",
"blockstudio": {
"attributes": []
}
}
Piekļuve lauku vērtībām
Šī ir visbiežākā izmaiņa, ko veiksiet pārejas laikā.
| ACF | Blockstudio |
|---|---|
get_field('title') |
$a['title'] |
get_field('title', $post_id) |
$a['title'] (vienmēr pieejams) |
the_field('title') |
<?php echo $a['title']; ?> |
have_rows('items') / the_row() |
foreach ($a['items'] as $item) |
get_sub_field('name') |
$item['name'] |
Mainīgais $a ir saīsinājums no $attributes un satur visas pašreizējā bloka lauku vērtības. Tas vienmēr ir pieejams veidnē gan redaktorā, gan priekšgalā.
Veidnes mainīgie
Blockstudio nodrošina vairākus mainīgos katrā veidnē:
| Mainīgais | Saīsinājums | Apraksts |
|---|---|---|
$attributes |
$a |
Visas lauku vērtības |
$block |
$b |
Bloka metadati (nosaukums, virsraksts, dir, url, postId) |
$context |
$c |
Vecākbloka konteksts |
$content |
InnerBlocks saturs | |
$post_id |
Pašreizējā ieraksta ID (darbojas redaktorā un priekšgalā; post_id vai postId iekš Twig) |
Lauku tipu atbilsmes
Lielākajai daļai ACF lauku tipu ir tiešs ekvivalents Blockstudio. JSON sintakse atšķiras, taču jēdzieni atbilst cits citam.
Teksta un satura lauki
ACF:
['name' => 'title', 'type' => 'text', 'label' => 'Title', 'default_value' => 'Hello']
['name' => 'bio', 'type' => 'textarea', 'label' => 'Bio', 'rows' => 4]
['name' => 'content', 'type' => 'wysiwyg', 'label' => 'Content']
Blockstudio:
{ "id": "title", "type": "text", "label": "Title", "default": "Hello" }
{ "id": "bio", "type": "textarea", "label": "Bio", "rows": 4 }
{ "id": "content", "type": "wysiwyg", "label": "Content" }
Rediģējamam tekstam bloku redaktorā (nevis tikai teksta ievades laukam) izmantojiet tipu richtext ar komponentu <RichText />:
{ "id": "heading", "type": "richtext" }
<RichText attribute="heading" tag="h1" placeholder="Enter heading" />
Attēlu un failu lauki
ACF lauki image un file atbilst Blockstudio tipam files:
ACF:
['name' => 'photo', 'type' => 'image', 'return_format' => 'array']
['name' => 'gallery', 'type' => 'gallery', 'return_format' => 'array']
['name' => 'document', 'type' => 'file', 'return_format' => 'array']
Blockstudio:
{ "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"] }
Atgrieztā objekta struktūra ir līdzīga:
// ACF
$image = get_field('photo');
echo $image['url'];
echo $image['alt'];
// Blockstudio
echo $a['photo']['url'];
echo $a['photo']['alt'];
Pieejamie rekvizīti: ID, title, alt, caption, description, href, url, sizes. Izmēri ir norādīti sizes, piemēram, $a['photo']['sizes']['full-width'].
Atlasīšana, radio pogas un izvēles rūtiņas
ACF:
[
'name' => 'color',
'type' => 'select',
'choices' => ['red' => 'Red', 'blue' => 'Blue'],
'return_format' => 'value',
]
Blockstudio:
{
"id": "color",
"type": "select",
"label": "Color",
"options": [
{ "value": "red", "label": "Red" },
{ "value": "blue", "label": "Blue" }
]
}
Izmantojiet "returnFormat": "both", lai iegūtu gan vērtību, gan etiķeti:
echo $a['color']['value']; // "red"
echo $a['color']['label']; // "Red"
Tas pats paņēmiens attiecas uz tipiem radio un checkbox.
Pārslēgšana un patiesa/nepatiesa vērtība
ACF:
['name' => 'show_cta', 'type' => 'true_false', 'label' => 'Show CTA']
Blockstudio:
{ "id": "showCta", "type": "toggle", "label": "Show CTA" }
Saites lauks
ACF:
['name' => 'cta', 'type' => 'link', 'return_format' => 'array']
// Template
$link = get_field('cta');
echo $link['url'];
echo $link['title'];
echo $link['target'];
Blockstudio:
{ "id": "cta", "type": "link", "label": "CTA", "opensInNewTab": true }
echo $a['cta']['url'];
echo $a['cta']['title'];
echo $a['cta']['target'];
Krāsa un gradients
ACF:
['name' => 'bgColor', 'type' => 'color_picker', 'label' => 'Background']
Blockstudio:
{ "id": "bgColor", "type": "color", "label": "Background" }
{ "id": "bgGradient", "type": "gradient", "label": "Background Gradient" }
Tips color ir integrēts ar WordPress krāsu paleti. Tips gradient nodrošina gradienta atlasītāju.
Skaitlis, diapazons un datums
ACF:
['name' => 'count', 'type' => 'number', 'min' => 1, 'max' => 10]
['name' => 'opacity', 'type' => 'range', 'min' => 0, 'max' => 100, 'step' => 5]
['name' => 'eventDate', 'type' => 'date_picker']
Blockstudio:
{ "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" }
Atkārtotāji
ACF atkārtotāja lauks tieši atbilst tipam repeater Blockstudio. ACF veidnēs parasti izmanto ciklu ar have_rows() / the_row() / get_sub_field() (atkārtotāja gadījumā get_field() arī atgriež rindu masīvu); Blockstudio ir pieejams tikai vienkāršais PHP masīvs, kas jau ir $a formātā.
ACF:
['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:
{
"id": "features",
"type": "repeater",
"label": "Features",
"min": 1,
"max": 10,
"attributes": [
{ "id": "title", "type": "text", "label": "Title" },
{ "id": "description", "type": "textarea", "label": "Description" }
]
}
<?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 atkārtotāji atbalsta ligzdošanu (atkārtotājs atkārtotājā) līdz 3 līmeņiem.
Grupas
ACF grupas lauks atbilst tipam group Blockstudio. Grupu lauku ID ir papildināti ar grupas ID prefiksu.
ACF:
['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:
{
"id": "author",
"type": "group",
"title": "Author",
"attributes": [
{ "id": "name", "type": "text", "label": "Name" },
{ "id": "role", "type": "text", "label": "Role" }
]
}
<?php $author = bs_get_group($a, 'author'); ?>
<p><?php echo esc_html($author['name']); ?></p>
<p><?php echo esc_html($author['role']); ?></p>
Palīgfunkcija bs_get_group() noņem grupas prefiksu no lauku ID, nodrošinot ērtu piekļuvi. Bez tās laukiem piekļūtu kā $a['author_name'] un $a['author_role'].
Nosacījumu loģika
Gan ACF, gan Blockstudio atbalsta nosacījumu loģiku lauku rādīšanai un paslēpšanai atkarībā no citu lauku vērtībām.
ACF:
['name' => 'showSubtitle', 'type' => 'true_false'],
[
'name' => 'subtitle',
'type' => 'text',
'conditional_logic' => [[['field' => 'field_showSubtitle', 'operator' => '==', 'value' => '1']]]
]
Blockstudio:
{ "id": "showSubtitle", "type": "toggle", "label": "Show Subtitle" },
{
"id": "subtitle",
"type": "text",
"label": "Subtitle",
"conditions": [[{ "id": "showSubtitle", "operator": "==", "value": true }]]
}
Blockstudio nosacījumos tieši norāda lauku ID (nevis lauku atslēgas). Pieejamie operatori: ==, !=, includes, !includes, empty, !empty, <, >, <=, >=.
Blockstudio atbalsta arī globālus nosacījumus, kuru pamatā ir ieraksta veids, ieraksta ID, lietotāja loma un lietotāja ID:
{
"conditions": [[{ "type": "postType", "operator": "==", "value": "page" }]]
}
InnerBlocks
Gan ACF, gan Blockstudio atbalsta InnerBlocks citu bloku ligzdošanai pielāgotajā blokā, izmantojot to pašu tagu <InnerBlocks /> un tos pašus atribūtus allowedBlocks, template un templateLock, tāpēc šī veidnes daļa parasti nav jāmaina.
Blockstudio:
<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>
Tags <InnerBlocks /> redaktorā tiek aizstāts ar komponentu React, bet priekšgalā — ar attēloto bloka saturu.
Ieraksta metadatu glabāšana
Gan ACF Blocks, gan Blockstudio pēc noklusējuma saglabā lauku vērtības kā bloka atribūtus ziņas saturā, nevis ziņas metadatos. Tas nozīmē, ka lauku vērtībām nevar veikt vaicājumus ar WP_Query, ja vien neizvēlaties metadatu glabāšanu.
ACF pievienoja izvēles ziņas metadatu glabāšanu blokiem ACF PRO 6.3 versijā, izmantojot usePostMeta: true, vienam augšējā līmeņa blokam katrā lapā. Blockstudio piedāvā katram laukam atsevišķu izvēles mehānismu, izmantojot rekvizītu storage:
{
"id": "featured",
"type": "toggle",
"label": "Featured",
"storage": {
"type": "postMeta",
"postMetaKey": "is_featured"
}
}
Metadatu atslēga tiek automātiski reģistrēta ar show_in_rest. Piekļūstiet tai jebkur, izmantojot get_post_meta($post_id, 'is_featured', true).
Visai vietnei paredzētām vērtībām (piemēram, ACF opciju lapām) izmantojiet opciju glabātuvi:
{
"storage": {
"type": "option",
"optionKey": "site_company_name"
}
}
Esošo bloku paplašināšana
ACF bloku atrašanās vietas noteikums piesaista lauku grupas tikai ACF blokiem; tas nepievieno laukus pamata vai trešo pušu blokiem. ACF veids, kā pievienot laukus pamata blokiem, piemēram, virsrakstam, rindkopai, attēlam un pogai, ir WordPress Block Bindings API, kas sasaista esošos bloku atribūtus ar ACF lauku vērtībām. Blockstudio var pievienot jaunus laukus un vadīklas jebkuram reģistrētam blokam, izmantojot paplašinājumu failus.
Izveidojiet paplašinājuma failu savā blockstudio direktorijā:
{
"name": "core/heading",
"blockstudio": {
"extend": true,
"attributes": [
{
"id": "accentColor",
"type": "color",
"label": "Accent Color",
"set": [{ "attribute": "style", "value": "color: {attributes.accentColor}" }]
}
]
}
}
Rekvizīts set automātiski piešķir lauka vērtību bloka HTML. Izmantojiet aizstājējzīmes, lai vienlaikus paplašinātu vairākus blokus: "name": "core/*".
Migrācijas kontrolsaraksts
- Izveidojiet bloka mapi mapē
theme/blockstudio/{block-name}/, iekļaujotblock.jsonunindex.php. - Pārvietojiet lauku definīcijas no bloka lauku grupas (Local JSON,
acf_add_local_field_group()vai iekļautaacf.fieldsmasīva) uz masīvublockstudio.attributesfailāblock.json. Mainietnameuzid, noņemietkeyun pēc vajadzības pielāgojiet tipu nosaukumus. - Atjauniniet piekļuvi veidnei no
get_field('name')uz$a['name']. Aizstājiethave_rows()ciklus arforeach ($a['repeater'] as $item). - Aizstājiet
get_sub_field()ar tiešu piekļuvi masīvam:$item['fieldId']. - Pievienojiet
useBlockPropsveidnes ārējam elementam, lai nodrošinātu pareizu integrāciju redaktorā. - Pārvietojiet nosacījumu loģiku no ACF
conditional_logicuz Blockstudioconditions, atsaucoties uz lauku ID, nevis lauku atslēgām. - Pievienojiet glabāšanu visiem laukiem, kuru vērtības iepriekš tika vaicātas ar
get_post_meta()vai izmantotasWP_Query. - Noņemiet ACF reģistrācijas kodu:
register_block_type()izsaukumus un migrēto blokuacfatslēgas (vai toacf_register_block_type()izsaukumus), kā arī to lauku grupas — neatkarīgi no tā, vai tās atrodas Local JSON,acf_add_local_field_group(), iekļautāacf.fieldsmasīvā vai administrācijas panelī. - Pārbaudiet redaktorā, vai lauki tiek attēloti pareizi, un pēc tam pārbaudiet vietnes saskarnes izvadi.