...

/

Building a Custom Button Block

Building a Custom Button Block

Learn to create a PHP class to generalize the block creation process.

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.

<?php
class ExcellenceBlock {
function __construct( ){
}
}
ExcellenceBlock class

We can create instances of the class by providing a name. For example:

<?php
new ExcellenceBlock("heading");
Create object of ExcellenceBlock class

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.

<?php
class ExcellenceBlock {
public $name;
function __construct( $name ){
$this->name = $name;
}
}
Constructor of ExcellenceBlock class

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.

<?php
class ExcellenceBlock {
public $name;
function __construct( $name ){
$this->name = $name;
add_action('init', [$this, 'excellence_block_init']);
}
function excellence_block_init(){
}
}
'init' hook to register the block
...