Modern Fields lets another plugin add its own field type. Your field shows up in the field group editor next to the native ones, with the same label, description, Required badge and settings panels, and its value is saved like any other field.
A field type is made of two parts: a block, which holds the settings of the field in the field group editor, and a field component, the input the user fills in. One function registers both: window.modernFields.fields.registerFieldType(), available since Modern Fields 1.4.0.
Declare the block
Describe your field in a block.json file, like any WordPress block. Its attributes are the settings of your field. The category places it in the inserter: mf-input-fields, mf-select-fields, mf-media-fields, mf-date-fields, mf-advanced-fields or mf-design-fields.
Register the script
In your plugin, register the script and the block. Add modern-fields-render-api to the dependencies of your script: it guarantees that the Modern Fields API is loaded before your code runs.
Register the field type
registerFieldType() takes the block metadata, an icon, and two components:
- Edit: the settings of your field, shown in the field group editor. Only render what is specific to your field: the label, the description and the common panels are added around it.
- Field: the input filled by the user. It reads and writes the value with
useFieldValue(), inside aFieldWrapperwhich displays the label and the description.
Your field now appears in the inserter of the field group editor, and its value is read in templates with get_field() like any other.
Type and sanitize the value
The type of the stored value is the type of the defaultValue attribute of your block: string when you don't declare it, number in the example above, or boolean, array, object.
Two PHP filters refine this. Both receive the field as an object: read its block with $field->getBlockName() and its settings with $field->getAttribute().
modern-fields/meta/sanitize_callbackchanges the function sanitizing the value before it is saved.modern-fields/meta/schemadescribes the content of anarrayorobjectvalue: its items or its properties.
What is stable, and what is not
window.modernFields.fields.registerFieldType()is the public API. Its signature will not change withoutwindow.modernFields.apiVersionchanging too.window.modernFields.internal, whereFieldWrapperanduseFieldValuelive for now, is not covered by that promise: these two helpers may move in a later version.- Your script is loaded where the block editor is: the field group editor and the post editor. On locations outside the block editor, such as options pages, terms and users, enqueue your script yourself.