GCBGutenberg
Control Blocks
v1.3.3
Buy

Make your own field type for the block editor

Add a custom control to Gutenberg Control Blocks: declare it in PHP, draw it with a React component, use it in any block.

Gutenberg Control Blocks (GCB) ships 42 field types, from text and images to repeaters and layouts. Sometimes a block needs a control that isn't on the list: a star rating, a seat picker, a timeline your client drags. You can add your own field type from a theme or plugin, without touching GCB, and then use it in any block like a built-in one.

A field type has two halves, and both are small:

  • PHP declares it. It gives the type a name, the shape of the value it saves, and the script that draws it.
  • JavaScript draws it. A React component shows the control in the editor and hands back the new value.

This guide builds a stars field that saves a rating from 1 to 5.

1. Declare the type in PHP

Register the type on the gcblite_register_control_types action with gcblite_register_control_type(). Register the editor script as usual on init, and pass its handle as script:

stars-field.php
<?phpadd_action('init', function () {    wp_register_script(        'my-stars-control',        plugins_url('stars.js', __FILE__),        ['wp-element', 'wp-components'],        '1.0',        true    );}); add_action('gcblite_register_control_types', function () {    gcblite_register_control_type('stars', [        'shape'  => 'integer',                       // string, number, integer, boolean, object or array        'script' => 'my-stars-control',              // loaded wherever GCB's field editors are        'doc'    => __DIR__ . '/fields/stars.md',     // optional    ]);});

Use this action, not a later hook. It fires on init at priority 4, and GCB types every block's attributes at priority 5. If you register a type later, its attribute is stored as a string and WordPress reports a _doing_it_wrong notice.

A few rules for the name:

  • It must be lowercase letters, digits and dashes.
  • It can't be a name GCB already uses, such as text or image.

Registering the type does three things:

  • The block attribute is typed as the shape you gave.
  • GCB's validator accepts the new name in block.fields.json.
  • With a doc file, the type joins the documented list of field types. The file uses the same frontmatter as the docs for GCB's own field types, so copy one of those as a start.

You can also add types with the gcblite_control_types filter instead of calling the function. It takes the same entries, keyed by type: 'stars' => ['shape' => …, 'doc' => …, 'script' => …]. Entries for built-in types are ignored.

2. Draw it in JavaScript

Your script registers a component with window.gcbLiteControls.register(). GCB loads it after its control hub, so the hub is always there when your script runs. The component gets the same props as every GCB control: control (the field's entry from block.fields.json), value, onChange and attributes.

This version uses WordPress's own wp.element and wp.components, so there's no build step:

stars.js
( function ( wp ) {    var el = wp.element.createElement;    var BaseControl = wp.components.BaseControl;    var Button = wp.components.Button;     window.gcbLiteControls.register( 'stars', function Stars( props ) {        var value = props.value || 0;        var stars = [];        for ( var i = 1; i <= 5; i++ ) {            stars.push( el( Button, {                key: i,                isPressed: i <= value,                'aria-label': i + ' out of 5',                onClick: props.onChange.bind( null, i )            }, '★' ) );        }        return el( BaseControl, { label: props.control.label, help: props.control.helpText }, stars );    } );} )( window.wp );

Your component draws its own label, the same way GCB's built-in controls do. If you'd rather write JSX, build the file with your usual tools. GCB only needs the registered component.

register() won't replace a built-in or GCB's own control unless you ask it to with { override: true } as the third argument. Use that only when you mean to swap a built-in control for your own.

3. Use it in a block

The new type works like any other, in block.fields.json:

block.fields.json
{  "controls": [    { "id": "c_rating", "type": "stars", "label": "Rating",      "attributeKey": "rating", "default": 5 }  ]}

The template reads it from $attributes:

render.php
<?php $rating = (int) ($attributes['rating'] ?? 0); ?><p <?php echo get_block_wrapper_attributes(['class' => 'review-stars']); ?>>  <?php echo esc_html(str_repeat('★', $rating)); ?>  <span class="screen-reader-text"><?php echo esc_html("$rating out of 5"); ?></span></p>

Your client sees the stars in the block's sidebar, and the preview updates as they click. The same type also works in post fields and in the sidebar panel, because every GCB field editor reads from the same hub.

Fields that need something from the block

Some fields only make sense with something else in the block. A timeline might need a <Repeater> of milestones to lay out. Add a check callable to say so, and return a message for each problem:

timeline-field.php
gcblite_register_control_type('timeline', [    'shape'  => 'array',    'script' => 'my-timeline-control',    'check'  => function (array $control, array $ctx) {        // $ctx: block, controls (this block's), children (what its <Repeater>s allow),        //       fields_of (a callable that reads another block's controls)        return $ctx['children'] ? [] : ['a timeline needs a <Repeater> of milestones.'];    },]);

With WP_DEBUG on, each message shows as a warning while blocks load, so you find the mistake when you build the block, not when your client uses it. Say what to fix in each message. GCB's own pin-map and layout fields use the same check.

When to make your own type

Check the field reference first. A lot of "custom" controls are already there: range for a slider, toggle-group for a small set of choices, point for a spot on a picture, repeater for rows. Make your own type when the value has its own shape or the control has to work in a way none of these do.

Try it

Adding your own field type covers the registry in full. The JavaScript API lists the hub's methods, and Hooks lists the action and filter. New to GCB? Start with the Quickstart.

Build anything in the block editor

Every licence includes all features and a year of updates and support.

Buy GCB from $8.25 a month See pricing