What are Attributes?
Attributes are the structured data needs of a block. They can exist in different forms when serialized, but are declared together under a common interface. For example, rich content, image URLs, background colors, or button titles.Defining Attributes
Attributes are specified in theattributes field - an object where each key is the attribute name, and the value is the attribute definition.
Accessing Attributes
Attributes are available in both theedit and save functions:
Type Validation
Thetype indicates the type of data stored by the attribute. A type is required unless an enum is provided.
Valid types:
nullbooleanobjectarraystringintegernumber(same asinteger)
Enum Validation
An attribute can be restricted to a fixed set of values usingenum:
Attribute Sources
Attribute sources define how attribute values are extracted from saved post content.No Source (Comment Delimiter)
When nosource is specified, data is stored in the block’s comment delimiter:
Attribute Source
Extract values from HTML element attributes:Boolean Attributes
For boolean HTML attributes likedisabled:
Text Source
Extract inner text from markup (usestextContent):
HTML Source
Extract inner HTML from markup (usesinnerHTML):
Query Source
Extract an array of values from multiple elements:Selectors
Theselector can be any valid CSS selector:
Default Values
Provide default values that are used when the attribute isn’t found in content:Attribute Roles
Therole property designates an attribute’s conceptual type:
Content Role
Marks attributes as user-editable content:content role attributes may be enabled for privileged editing in special circumstances like content-only locking.
Local Role
Marks attributes as temporary and non-persistable:local role are ignored by the Block Serializer and never saved to post content.
Updating Attributes
UsesetAttributes to update attribute values in the editor:
Save Function Requirements
The block is responsible for ensuring attributes with asource field are saved correctly:
source are automatically saved in the block comment delimiter.
Complete Example
Best Practices
- Use appropriate sources: Store data in HTML when possible rather than comment delimiters to reduce data storage.
- Provide defaults: Always provide sensible default values for attributes.
- Match save and edit: Ensure your save function outputs the correct HTML structure for your attribute sources.
- Type carefully: Use the correct type for each attribute to ensure proper validation.
- Document attributes: Add comments to explain complex attribute structures.
Deprecated: Meta Source
For working with post meta, see the Create Meta Block guide.Related Documentation
- Block Deprecation - Handle attribute changes over time
- Block Supports - Auto-generated attributes
- Dynamic Blocks - Server-side attribute handling