Adding ReusableBlock To Admin Menu

ReusableBlock Class

Note

We need to make changes to the get_services function inside Init.php. It needs to return an array. This array can be empty for now, but we will add the Reusable class after we have created it.

Open the ReusableBlock.php file and add the following code.

Explaining the code.

We will start with the header comment to specify the package that is Domain_Core.

Add the namespace. This time it will be Domain_Core\Admin since we are in the Admin directory. The namespace should always match your folder names.

Create the ReusebaleBlocks class. Inside this class, we will add two functions.

  1. The register function/method
  2. The add_resusable_blocks_admin_menu

Let us look at what these two functions will execute.

The register function/method

In this function definition, we will add the admin_menu hook. This hook will invoke the add_reusable_blocks_admin_menu function that we have yet to define.

You recall that the Init class has the register_services function. This checks whether the instantiated classes have the register method, and after that, it invokes it.

For the ReusableBlocks class, this is the register method that gets to be invoked.

To improve on code readability, ensure to document your functions.

The add_resusable_blocks_admin_menu

Within the ReusableBlocks class ( but outside the register method), define the add_reusable_blocks_admin_menu function. This function displays the reusable blocks via the WP-Admin menu.

In the code gist above, we defined the function from lines 23 – 25.

Read more about this function/snippet from this article: Reusable Blocks accessible in WordPress admin area.

This code snippet will add the reusable block menu to your admin screen.

Register the function inside Init.php

Go to the get_services function inside the Init.php file. Inside the empty array, the function returns, add the function the ReusableBlock class, but we do this using the namespace that is like this Admin\ReusableBlock::class.

Go to the get_services function inside the Init.php file. Go to the empty array that the function returns. Add the ReusableBlock class using the namespace Admin\ReusableBlock::class.

The Reusable Blocks menu item should now be visible on your WP-Admin menu.

Reusable Blocks Menu item on WP Admin Menu
The Reusable Blocks Menu item appearing on the WP Admin Menu