コンテンツへスキップ

フィールドパターンレシピ集

Blockstudioのフィールドシステムは、単独ではシンプルです。blockstudio.attributesにフィールドを追加し、テンプレートで$aを使ってアクセスします。しかし実際のブロックにフィールドが1つだけということはほとんどありません。関連する設定のグループ、他のフィールドの値に応じて表示・非表示が切り替わるフィールド、複雑な行構造を持つリピーター、ブロックエディターの外からクエリする必要があるデータなどがあります。

このガイドでは、よく使うフィールドパターンの実践的なレシピを紹介します。各レシピにはblock.jsonの設定と対応するテンプレートコードが含まれています。ブロックにそのままコピーし、必要に応じて調整してください。

条件付きフィールド

最も一般的なパターンは、別のフィールドの値に応じてフィールドを表示または非表示にすることです。関連するオプションだけを表示できるため、エディターがすっきりします。

切り替えでオプションを表示する

ボタンを有効にすると追加設定が表示されるCTAブロックの例です。

JSON
{
  "name": "my-theme/cta",
  "title": "Call to Action",
  "blockstudio": {
    "attributes": [
      { "id": "heading", "type": "text", "label": "Heading", "default": "Ready to get started?" },
      { "id": "description", "type": "textarea", "label": "Description" },
      { "id": "showButton", "type": "toggle", "label": "Show Button", "default": true },
      {
        "id": "buttonText",
        "type": "text",
        "label": "Button Text",
        "default": "Get Started",
        "conditions": [[{ "id": "showButton", "operator": "==", "value": true }]]
      },
      {
        "id": "buttonUrl",
        "type": "link",
        "label": "Button Link",
        "conditions": [[{ "id": "showButton", "operator": "==", "value": true }]]
      }
    ]
  }
}

ボタンのテキストとリンクのフィールドは、切り替えがオンのときだけ表示されます。テンプレートでは、表示前に切り替えの状態を確認します。

PHP
<div useBlockProps>
  <h2><?php echo esc_html( $a['heading'] ); ?></h2>
  <?php if ( $a['description'] ) : ?>
    <p><?php echo esc_html( $a['description'] ); ?></p>
  <?php endif; ?>
  <?php if ( $a['showButton'] && $a['buttonUrl'] ) : ?>
    <a href="<?php echo esc_url( $a['buttonUrl']['url'] ); ?>">
      <?php echo esc_html( $a['buttonText'] ); ?>
    </a>
  <?php endif; ?>
</div>

セレクトでフィールドセットを切り替える

背景の種類によって表示するフィールドが決まるヒーローブロックの例です。

JSON
{
  "name": "my-theme/hero",
  "title": "Hero",
  "blockstudio": {
    "attributes": [
      { "id": "heading", "type": "text", "label": "Heading" },
      {
        "id": "bgType",
        "type": "select",
        "label": "Background Type",
        "default": "color",
        "options": [
          { "value": "color", "label": "Solid Color" },
          { "value": "gradient", "label": "Gradient" },
          { "value": "image", "label": "Image" },
          { "value": "video", "label": "Video" }
        ]
      },
      {
        "id": "bgColor",
        "type": "color",
        "label": "Background Color",
        "conditions": [[{ "id": "bgType", "operator": "==", "value": "color" }]]
      },
      {
        "id": "bgGradient",
        "type": "gradient",
        "label": "Background Gradient",
        "conditions": [[{ "id": "bgType", "operator": "==", "value": "gradient" }]]
      },
      {
        "id": "bgImage",
        "type": "files",
        "label": "Background Image",
        "multiple": false,
        "conditions": [[{ "id": "bgType", "operator": "==", "value": "image" }]]
      },
      {
        "id": "bgVideo",
        "type": "files",
        "label": "Background Video",
        "multiple": false,
        "allowedTypes": ["video"],
        "conditions": [[{ "id": "bgType", "operator": "==", "value": "video" }]]
      },
      {
        "id": "overlay",
        "type": "range",
        "label": "Overlay Opacity",
        "default": 50,
        "min": 0,
        "max": 100,
        "conditions": [[{ "id": "bgType", "operator": "!=", "value": "color" }]]
      }
    ]
  }
}

オーバーレイの不透明度フィールドは!=を使い、単色以外の場合に表示します。一度に表示される背景フィールドは1つだけです。colorフィールドは色のvalue、name、slugを含む配列を返すため、テンプレートでは['value']を読み取ります。

PHP
<?php
$bg_style = match ( $a['bgType'] ) {
	'color'    => $a['bgColor'] ? "background-color: {$a['bgColor']['value']}" : '',
	'gradient' => $a['bgGradient'] ? "background: {$a['bgGradient']}" : '',
	'image'    => $a['bgImage'] ? "background-image: url({$a['bgImage']['url']})" : '',
	default    => '',
};
?>
<div useBlockProps style="<?php echo esc_attr( $bg_style ); ?>">
  <?php if ( $a['bgType'] === 'video' && $a['bgVideo'] ) : ?>
    <video autoplay muted loop playsinline>
      <source src="<?php echo esc_url( $a['bgVideo']['url'] ); ?>" />
    </video>
  <?php endif; ?>
  <h1><?php echo esc_html( $a['heading'] ); ?></h1>
</div>

OR条件

複数の条件のうち、いずれかが成立したときにフィールドを表示します。各内側の配列はANDグループで、外側の配列はそれらをORで組み合わせます。

JSON
{
  "id": "caption",
  "type": "text",
  "label": "Caption",
  "conditions": [
    [{ "id": "bgType", "operator": "==", "value": "image" }],
    [{ "id": "bgType", "operator": "==", "value": "video" }]
  ]
}

これにより、bgTypeが「image」または「video」の場合にキャプションフィールドが表示されます。

条件の連結

同じ内側の配列に複数の条件がある場合は、ANDロジックが使われます。

JSON
{
  "id": "altText",
  "type": "text",
  "label": "Alt Text",
  "conditions": [[
    { "id": "bgType", "operator": "==", "value": "image" },
    { "id": "bgImage", "operator": "!empty" }
  ]]
}

代替テキストフィールドは、bgTypeが「image」で、画像が選択されている場合にのみ表示されます。

グローバル条件

他のフィールドの値ではなく、投稿タイプ、投稿ID、ユーザーロールに基づいてフィールドを表示します。

JSON
{
  "id": "seoTitle",
  "type": "text",
  "label": "SEO Title",
  "conditions": [[{ "type": "postType", "operator": "==", "value": "page" }]]
}

利用可能なグローバル条件の種類:postType、postId、userRole、userId。

設定の整理

ブロックが複雑になるにつれて、フィールドを論理的なグループに整理するとインスペクターを使いやすく保てます。

見やすく整理するグループ

グループを使うと、インスペクターに折りたたみ可能なセクションを作成できます。名前のないグループ(idなし)は見た目を整理するためだけのもので、フィールドにはそのままのIDでアクセスします。

JSON
{
  "name": "my-theme/card",
  "title": "Card",
  "blockstudio": {
    "attributes": [
      {
        "type": "group",
        "title": "Content",
        "attributes": [
          { "id": "title", "type": "text", "label": "Title" },
          { "id": "description", "type": "textarea", "label": "Description" },
          { "id": "image", "type": "files", "label": "Image", "multiple": false }
        ]
      },
      {
        "type": "group",
        "title": "Link",
        "attributes": [
          { "id": "url", "type": "link", "label": "URL" },
          { "id": "openInNewTab", "type": "toggle", "label": "Open in New Tab" }
        ]
      },
      {
        "type": "group",
        "title": "Appearance",
        "attributes": [
          {
            "id": "style",
            "type": "select",
            "label": "Style",
            "default": "elevated",
            "options": [
              { "value": "elevated", "label": "Elevated" },
              { "value": "outlined", "label": "Outlined" },
              { "value": "flat", "label": "Flat" }
            ]
          },
          { "id": "accentColor", "type": "color", "label": "Accent Color" }
        ]
      }
    ]
  }
}
PHP
<div useBlockProps>
  <h3><?php echo esc_html( $a['title'] ); ?></h3>
  <p><?php echo esc_html( $a['description'] ); ?></p>
</div>

フィールドには直接アクセスできます:$a['title']、$a['style']、$a['accentColor']。グループが変えるのはインスペクターのレイアウトだけです。

bs_get_groupを使った名前付きグループ

グループにidがあると、子フィールドのIDにその名前が接頭辞として付きます。bs_get_group()を使って接頭辞を取り除きます。

JSON
{
  "id": "author",
  "type": "group",
  "title": "Author",
  "attributes": [
    { "id": "name", "type": "text", "label": "Name" },
    { "id": "role", "type": "text", "label": "Role" },
    { "id": "avatar", "type": "files", "label": "Avatar", "multiple": false }
  ]
}

ヘルパーを使わない場合、フィールドには$a['author_name']、$a['author_role']、$a['author_avatar']としてアクセスします。ヘルパーを使う場合:

PHP
<?php $author = bs_get_group( $a, 'author' ); ?>
<div class="author">
  <?php if ( $author['avatar'] ) : ?>
    <img src="<?php echo esc_url( $author['avatar']['url'] ); ?>" alt="" />
  <?php endif; ?>
  <p><?php echo esc_html( $author['name'] ); ?></p>
  <p><?php echo esc_html( $author['role'] ); ?></p>
</div>

同じフィールド名が複数のグループにある場合(e.g、author_name、company_nameなど)や、グループをひとまとまりとしてパーシャルテンプレートに渡したい場合に、名前付きグループが便利です。

グループ内のグリッドレイアウト

styleプロパティを使うと、グループの子フィールドを横並びにできます。

JSON
{
  "type": "group",
  "title": "Dimensions",
  "style": {
    "display": "grid",
    "grid-template-columns": "1fr 1fr",
    "grid-gap": "16px"
  },
  "attributes": [
    { "id": "width", "type": "unit", "label": "Width", "default": "100%", "switch": false },
    { "id": "height", "type": "unit", "label": "Height", "default": "auto", "switch": false }
  ]
}

2つの単位フィールドは、縦に積み重ねず、インスペクターで横並びに表示されます。寸法のペア、マージンとパディングの値など、概念上ひと組になる2つのフィールドに適しています。

大きなセクションをタブで分ける

ブロックの設定が多い場合、長いグループの一覧よりもタブで整理すると見やすくなります。

JSON
{
  "type": "tabs",
  "tabs": [
    {
      "title": "Content",
      "attributes": [
        { "id": "title", "type": "text", "label": "Title" },
        { "id": "body", "type": "wysiwyg", "label": "Body" }
      ]
    },
    {
      "title": "Media",
      "attributes": [
        { "id": "image", "type": "files", "label": "Image", "multiple": false },
        { "id": "video", "type": "files", "label": "Video", "multiple": false, "allowedTypes": ["video"] }
      ]
    },
    {
      "title": "Settings",
      "attributes": [
        { "id": "layout", "type": "select", "label": "Layout", "options": [
          { "value": "left", "label": "Media Left" },
          { "value": "right", "label": "Media Right" }
        ]},
        { "id": "fullWidth", "type": "toggle", "label": "Full Width" }
      ]
    }
  ]
}

各タブのフィールドにはトップレベルのフィールドと同様にアクセスできます: $a['title']、$a['image']、$a['layout']。タブは表示上のUIコンテナにすぎません。

リピーターのパターン

リピーターを使うと、ユーザーがフィールドの行を複数追加できます。リスト、グリッド、タイムライン、項目数が変動するコンポーネントに欠かせません。

制約付きの基本的なリピーター

項目数が1〜6件の特徴一覧:

JSON
{
  "id": "features",
  "type": "repeater",
  "label": "Features",
  "min": 1,
  "max": 6,
  "textButton": "Add Feature",
  "attributes": [
    { "id": "icon", "type": "icon", "label": "Icon" },
    { "id": "title", "type": "text", "label": "Title", "default": "Feature" },
    { "id": "description", "type": "textarea", "label": "Description" }
  ]
}
PHP
<div useBlockProps class="grid grid-cols-3 gap-8">
  <?php foreach ( $a['features'] as $feature ) : ?>
    <div>
      <?php if ( $feature['icon'] ) : ?>
        <?php bs_render_icon( $feature['icon'] ); ?>
      <?php endif; ?>
      <h3><?php echo esc_html( $feature['title'] ); ?></h3>
      <p><?php echo esc_html( $feature['description'] ); ?></p>
    </div>
  <?php endforeach; ?>
</div>

行のラベルをカスタマイズする

初期設定では、最小化したリピーターの行に一般的なラベルが表示されます。textMinimizedを使うと、代わりにフィールドの値を表示できます。

JSON
{
  "id": "team",
  "type": "repeater",
  "label": "Team Members",
  "textMinimized": { "id": "name", "fallback": "Team Member" },
  "attributes": [
    { "id": "name", "type": "text", "label": "Name" },
    { "id": "role", "type": "text", "label": "Role" },
    { "id": "photo", "type": "files", "label": "Photo", "multiple": false }
  ]
}

行を折りたたむと、「Row 1」の代わりに人物の名前が表示されます。名前フィールドが空の場合はfallbackが使われます。prefixとsuffixの文字列も追加できます。

リピーター内の条件

リピーター内のフィールドは、同じ行の他のフィールドを接頭辞なしのidで参照できます(接頭辞は不要です)。

JSON
{
  "id": "links",
  "type": "repeater",
  "label": "Links",
  "attributes": [
    { "id": "label", "type": "text", "label": "Label" },
    { "id": "url", "type": "link", "label": "URL" },
    {
      "id": "isExternal",
      "type": "toggle",
      "label": "External Link"
    },
    {
      "id": "externalNote",
      "type": "message",
      "label": "Note",
      "description": "External links open in a new tab with rel=\"noopener\".",
      "conditions": [[{ "id": "isExternal", "operator": "==", "value": true }]]
    }
  ]
}

リピーター内から外側のフィールドを参照する

リピーター内の条件でリピーターの外にあるフィールドを確認するには、"context": "main"を追加します。

JSON
{
  "id": "showDescriptions",
  "type": "toggle",
  "label": "Show Descriptions",
  "default": true
},
{
  "id": "items",
  "type": "repeater",
  "label": "Items",
  "attributes": [
    { "id": "title", "type": "text", "label": "Title" },
    {
      "id": "description",
      "type": "textarea",
      "label": "Description",
      "conditions": [[{
        "id": "showDescriptions",
        "operator": "==",
        "value": true,
        "context": "main"
      }]]
    }
  ]
}

"context": "main"がない場合、条件はリピーターの行内にあるshowDescriptionsフィールドを探します。追加すると、ルートレベルの切り替えを確認します。

リピーター内のタブ

リピーター内ではタブを使用できません。リピーター行のtabsフィールドは、フィールドの代わりにエディター内で通知を表示し、PHPStan拡張機能でもその旨が報告されます。行のフィールドはフラットに配置してください。行が長い場合は、カスタム行ラベル(textMinimized)を設定すると折りたたまれた行を読みやすくできます。また、上記のパターンのように、行内の条件を使って一部の行だけに必要なフィールドを非表示にできます。

リピーターに"minimized": trueを設定すると、既存の行を折りたたんだ状態で開始できます。新しく追加した行はすぐに開きます。展開した例外の状態は、エディターを再読み込みしてもこのブラウザーに記憶されます。これは編集時の設定であり、投稿コンテンツとして保存されるものではありません。minimizedを設定していないリピーターは、引き続きデフォルトで展開されます。

メディアのパターン

フォールバック付きの単一画像

JSON
{
  "id": "image",
  "type": "files",
  "label": "Image",
  "multiple": false
}
PHP
<?php if ( $a['image'] ) : ?>
  <img
    src="<?php echo esc_url( $a['image']['url'] ); ?>"
    alt="<?php echo esc_attr( $a['image']['alt'] ); ?>"
    <?php if ( isset( $a['image']['sizes']['full-width'], $a['image']['sizes']['full-height'] ) ) : ?>
      width="<?php echo esc_attr( $a['image']['sizes']['full-width'] ); ?>"
      height="<?php echo esc_attr( $a['image']['sizes']['full-height'] ); ?>"
    <?php endif; ?>
  />
<?php endif; ?>

デフォルトのreturnFormatは"object"で、ID、title、alt、caption、description、href、url、sizesを提供します。sizesには、登録済みの各画像サイズのURL(sizes['large'])と、その寸法(sizes['large-width']、sizes['large-height'])が格納されます。全項目の一覧はレンダリング属性を参照してください。

JSON
{
  "id": "gallery",
  "type": "files",
  "label": "Gallery",
  "multiple": true,
  "max": 6,
  "allowedTypes": ["image"]
}
PHP
<?php if ( $a['gallery'] ) : ?>
  <div class="grid grid-cols-3 gap-4">
    <?php foreach ( $a['gallery'] as $image ) : ?>
      <img
        src="<?php echo esc_url( $image['url'] ); ?>"
        alt="<?php echo esc_attr( $image['alt'] ); ?>" />
    <?php endforeach; ?>
  </div>
<?php endif; ?>

切り替えで無効にできる画像

switchプロパティを使うと目のアイコンが追加され、値を削除せずにフィールドを無効にできます。

JSON
{
  "id": "logo",
  "type": "files",
  "label": "Logo",
  "multiple": false,
  "switch": true
}
PHP
<?php
$is_disabled = ! empty( $a['_disabled'] ) && in_array( 'logo', $a['_disabled'], true );
if ( $a['logo'] && ! $is_disabled ) : ?>
  <img src="<?php echo esc_url( $a['logo']['url'] ); ?>" alt="" />
<?php endif; ?>

ユーザーはアップロード済みファイルを削除せずにロゴをオフにできます。再び有効にすると、同じファイルが表示されます。

返り値の形式

ファイルフィールドの返り値を指定します。

JSON
// Full object (default)
{ "id": "photo", "type": "files", "returnFormat": "object", "multiple": false }
// $a['photo']['url'], $a['photo']['alt'], $a['photo']['sizes']['full-width'], etc.

// Just the ID
{ "id": "photo", "type": "files", "returnFormat": "id", "multiple": false }
// $a['photo'] = 42

// Just the URL
{ "id": "photo", "type": "files", "returnFormat": "url", "multiple": false }
// $a['photo'] = "https://example.com/photo.jpg"

wp_get_attachment_image()を自分で呼び出す必要がある場合は"id"を使います。単純な背景画像には"url"を使います。それ以外は"object"(初期設定)を使います。

"returnFormat": "id"を使うと、"buckshair-home"のようなインポートされた文字列参照はそのまま渡されます。エディターでは、リピーター行を含め、サムネイルのないフォールバックカードが表示されます。ページを開いたり保存したりしても、スカラー参照が配列に変換されることはありません。添付ファイルIDと文字列参照が混在するリストも使用できます。メディアライブラリで検索されるのは正の添付ファイルIDのみです。

Blockstudioは、カスタム文字列参照を添付ファイルに解決しません。サイト間で移植可能な名前を使う場合は、独自のレンダーフィルターまたはテンプレートで解決してください。メディアライブラリで置き換え先を選ぶと、通常どおり添付ファイルIDが保存されます。

動的オプション

投稿から入力する

公開済みのページをすべて一覧表示するセレクトフィールド:

JSON
{
  "id": "linkedPage",
  "type": "select",
  "label": "Linked Page",
  "stylisedUi": true,
  "populate": {
    "type": "query",
    "query": "posts",
    "arguments": {
      "post_type": "page",
      "post_status": "publish",
      "posts_per_page": -1
    }
  }
}

このフィールドには、ページタイトルをラベル、投稿IDを値として自動入力します。populate設定にreturnFormatを使うと、マッピングをカスタマイズできます。

JSON
"populate": {
  "type": "query",
  "query": "posts",
  "arguments": { "post_type": "page" },
  "returnFormat": { "value": "ID", "label": "post_title" }
}

タクソノミーのタームから入力する

JSON
{
  "id": "category",
  "type": "select",
  "label": "Category",
  "stylisedUi": true,
  "populate": {
    "type": "query",
    "query": "terms",
    "arguments": {
      "taxonomy": "category",
      "hide_empty": true
    }
  }
}

PHP関数から入力する

JSON
{
  "id": "postType",
  "type": "select",
  "label": "Post Type",
  "populate": {
    "type": "function",
    "function": "get_post_types",
    "arguments": { "public": true }
  }
}

静的オプションに入力済みの項目を追加する

ハードコードしたオプションと動的なオプションを組み合わせます。positionを使うと、入力したオプションの表示位置を指定できます。

JSON
{
  "id": "source",
  "type": "select",
  "label": "Source",
  "options": [
    { "value": "manual", "label": "Manual Entry" },
    { "value": "latest", "label": "Latest Posts" }
  ],
  "populate": {
    "type": "query",
    "query": "posts",
    "arguments": { "post_type": "page" },
    "position": "after"
  }
}

静的なオプションの後に、動的に入力されたページが表示されます。

クエリ用のデータ保存

初期設定では、フィールドの値はpost_content内のブロック属性に保存されます。WP_Queryではクエリできません。フィールドの値で投稿を絞り込んだり並べ替えたりするには、ストレージを使います。

クエリ可能なフィールドの投稿メタ

JSON
{
  "id": "featured",
  "type": "toggle",
  "label": "Featured",
  "storage": {
    "type": "postMeta",
    "postMetaKey": "is_featured"
  }
},
{
  "id": "priority",
  "type": "number",
  "label": "Priority",
  "default": 0,
  "min": 0,
  "max": 100,
  "storage": {
    "type": "postMeta",
    "postMetaKey": "priority_score"
  }
}

これで、注目の投稿をクエリできます。

PHP
$featured = new WP_Query( array(
    'meta_query' => array(
        array(
            'key'   => 'is_featured',
            'value' => '1',
        ),
    ),
    'orderby'  => 'meta_value_num',
    'meta_key' => 'priority_score',
    'order'    => 'DESC',
) );

メタキーはshow_in_restに自動登録されるため、RESTAPIでも使用できます。

二重保存

ブロック属性と投稿メタの両方に保存します。ブロック属性に値があればテンプレート内で$aを使え、投稿メタに保存すればクエリ可能になります。

JSON
{
  "id": "eventDate",
  "type": "date",
  "label": "Event Date",
  "storage": {
    "type": ["block", "postMeta"],
    "postMetaKey": "event_date"
  }
}

グローバル値のオプション保存

サイト全体で共通にする設定には、オプション保存を使います。

JSON
{
  "id": "companyName",
  "type": "text",
  "label": "Company Name",
  "storage": {
    "type": "option",
    "optionKey": "site_company_name"
  }
}

値はwp_optionsに保存され、どこからでもget_option('site_company_name')でアクセスできます。ユーザーがどのブロックのインスタンスでこのフィールドを編集しても、値は全体に反映されます。

再利用可能なフィールド定義

複数のブロックで同じフィールド構成を使う場合は、カスタムフィールドとして一度定義し、どこからでも参照できます。

カスタムフィールドを作成する

テーマのblockstudio/fields/ディレクトリにfield.jsonを作成します。

コード
theme/
└── blockstudio/
    └── fields/
        └── cta/
            └── field.json
JSON
{
  "name": "cta",
  "title": "Call to Action",
  "attributes": [
    { "id": "label", "type": "text", "label": "Button Label", "default": "Learn More" },
    { "id": "url", "type": "link", "label": "Button URL" },
    { "id": "style", "type": "select", "label": "Button Style", "default": "primary", "options": [
      { "value": "primary", "label": "Primary" },
      { "value": "secondary", "label": "Secondary" },
      { "value": "outline", "label": "Outline" }
    ]}
  ]
}

カスタムフィールドを使う

"type": "custom/cta"を使って、任意のブロックから参照します。

JSON
{
  "blockstudio": {
    "attributes": [
      { "id": "heading", "type": "text", "label": "Heading" },
      { "type": "custom/cta" }
    ]
  }
}

CTAフィールドはブロックにインラインで組み込まれます。$a['label']、$a['url']、$a['style']で直接アクセスできます。

idStructureを使った接頭辞付きカスタムフィールド

同じカスタムフィールドを複数回使う場合は、idStructureを追加してIDに接頭辞を付けます。

JSON
{
  "blockstudio": {
    "attributes": [
      { "type": "custom/cta", "idStructure": "primary_{id}" },
      { "type": "custom/cta", "idStructure": "secondary_{id}" }
    ]
  }
}

1つ目のCTAのフィールドはprimary_label、primary_url、primary_styleになります。2つ目はsecondary_labelなどになります。

初期値を上書きする

カスタムフィールドを参照する際に、特定のフィールドをカスタマイズできます。

JSON
{
  "type": "custom/cta",
  "idStructure": "hero_{id}",
  "overrides": {
    "label": { "default": "Get Started", "label": "CTA Label" },
    "style": { "default": "primary" }
  }
}

上書き設定は元の定義に追加されます。初期値、ラベル、条件、その他のプロパティを変更できます。

レンダリングのパターン

空の値を確認する

ほとんどのフィールドタイプは、空の場合falseを返します。レンダリング前に必ず確認してください。

PHP
<?php if ( $a['title'] ) : ?>
  <h2><?php echo esc_html( $a['title'] ); ?></h2>
<?php endif; ?>

数値の場合、0は有効な値です。「空」と「ゼロ」を区別する必要があれば、厳密な比較を使います。

PHP
<?php if ( $a['count'] !== 0 || $a['count'] !== false ) : ?>
  <span><?php echo esc_html( $a['count'] ); ?></span>
<?php endif; ?>

returnFormat: bothを使ったセレクト

ロジック用の値と表示用のラベルの両方が必要な場合:

JSON
{
  "id": "status",
  "type": "select",
  "label": "Status",
  "returnFormat": "both",
  "options": [
    { "value": "active", "label": "Active" },
    { "value": "paused", "label": "On Hold" },
    { "value": "closed", "label": "Closed" }
  ]
}
PHP
<?php if ( $a['status'] ) : ?>
  <span class="badge badge--<?php echo esc_attr( $a['status']['value'] ); ?>">
    <?php echo esc_html( $a['status']['label'] ); ?>
  </span>
<?php endif; ?>

attributesフィールドからデータ属性を設定する

attributesフィールドタイプを使うと、ユーザーがカスタムデータ属性を追加できます。

JSON
{
  "id": "dataAttrs",
  "type": "attributes",
  "label": "Data Attributes",
  "link": true,
  "media": true
}
PHP
<div useBlockProps <?php bs_render_data_attributes( $a['dataAttrs'] ); ?>>
  Content here.
</div>

フィールド値からCSS変数を作る

選択したフィールドからCSSカスタムプロパティを生成します。

JSON
{
  "id": "textColor", "type": "color", "label": "Text Color"
},
{
  "id": "fontSize", "type": "unit", "label": "Font Size", "default": "1rem"
}
PHP
<div useBlockProps style="<?php bs_render_variables( $a, array( 'textColor', 'fontSize' ) ); ?>">
  <p>Styled content.</p>
</div>

出力例はstyle="--text-color: #333; --font-size: 1rem;"です(フィールドIDはケバブケースに変換されます)。CSSで変数を使います。

CSS
p {
  color: var(--text-color);
  font-size: var(--font-size);
}

次のステップ