Building a Custom Button Block
Explore how to create a reusable custom button block in WordPress by using a PHP class to register blocks dynamically. Learn to organize block files, configure metadata via block.json, and implement edit and save components with React, enabling you to add styled buttons to your WordPress site.
We will create a block that adds a button with our theme's styling.
Using a PHP class for block registration
Since we will be defining multiple blocks for our theme, instead of registering them one by one, we can create a PHP class to reduce code duplication. This will also help avoid naming conflicts with other functions and variables of WordPress or any third party plugins.
In functions.php, create a class called ExcellenceBlock. The class will have a __construct function which includes the action and filter hooks.
<?phpclass ExcellenceBlock {function __construct( ){}}
We can create instances of the class by providing a name. For example:
<?phpnew ExcellenceBlock("heading");
Inside the constructor, we will initialize the name of the block from the input parameter. The only thing that changes with every block is its name. We need to define a property name for the block.
<?phpclass ExcellenceBlock {public $name;function __construct( $name ){$this->name = $name;}}
Next, add an action on the init hook to register the block. Since we are using a PHP class, we will use the array callable syntax to call the excellence_block_init function at the init hook.
<?phpclass ExcellenceBlock {public $name;function __construct( $name ){$this->name = $name;add_action('init', [$this, 'excellence_block_init']);}function excellence_block_init(){}}
Now modify the excellence_blocks_init function which ...