0
0
Wordpressframework~30 mins

Block attributes and controls in Wordpress - Mini Project: Build & Apply

Choose your learning style9 modes available
WordPress Block Attributes and Controls
📖 Scenario: You are creating a custom WordPress block for a blog editor. This block will allow users to enter a title and a description. You want to store these inputs as block attributes and provide controls in the block editor to update them.
🎯 Goal: Build a simple WordPress block that has two attributes: title and description. Add controls in the block editor sidebar to edit these attributes. The block should display the title as a heading and the description as a paragraph.
📋 What You'll Learn
Create block attributes title and description with default empty strings
Add controls in the block editor sidebar to update title and description
Render the block output showing the title in an <h2> and the description in a <p>
Use functional components and hooks as per WordPress block editor standards
💡 Why This Matters
🌍 Real World
Custom WordPress blocks let content creators add specialized content easily with tailored controls and saved data.
💼 Career
Understanding block attributes and controls is essential for WordPress developers building custom blocks for clients or themes.
Progress0 / 4 steps
1
Set up block attributes
Create a block attributes object called attributes with two attributes: title and description. Both should have a type of string and default to an empty string ''.
Wordpress
Need a hint?

Use an object named attributes with keys title and description. Each should have type: 'string' and default: ''.

2
Add block controls for title and description
Create a functional component called Edit that receives attributes and setAttributes as props. Add two TextControl components from @wordpress/components to edit title and description. Use attributes.title and attributes.description as their values, and update them using setAttributes on change.
Wordpress
Need a hint?

Use two TextControl components with label, value, and onChange props. Update attributes using setAttributes.

3
Render the block output
Create a functional component called Save that receives attributes as a prop. Return JSX that renders an <h2> with attributes.title and a <p> with attributes.description.
Wordpress
Need a hint?

Return JSX with an <h2> showing attributes.title and a <p> showing attributes.description.

4
Register the block with attributes, edit, and save
Use registerBlockType from @wordpress/blocks to register a block with name 'myplugin/custom-block'. Pass the attributes object, and set the edit property to the Edit component and the save property to the Save component.
Wordpress
Need a hint?

Call registerBlockType with the block name, pass attributes, and assign Edit and Save components to edit and save respectively.