Magento 2: Creating CMS Static Block Using Installable Script

Magento 2 provides the navigate feature on the admin side to add CMS static blocks. But while you are developing an extension, you might need to create the installable script to add new CMS static block. Creating installable scripts in Magento 2 is not a big work, and this article will help you if you are not familiar with creating the CMS static blocks using an installable script.

Step 1: Module Registration

In order to create a new module, create a registration.php file in the below file path based on the Magento 2 structure,

Sample File Path: app/code/BlogTreat/YourModule/registration.php


Step 2: Module Configuration

Create a file named module.xml in the below file path to define new Magento 2 extension

Sample File Path: app/code/BlogTreat/YourModule/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="BlogTreat_YourModule" setup_version="1.0.0">

Step 3: Create a Setup File

Create a setup file named InstallData.php in the below file path, and in this file, we have to provide all the information about our new CMS static block.

Sample File Path: app/code/BlogTreat/YourModule/Setup/InstallData.php

namespace BlogTreat\YourModule\Setup;

use Magento\Cms\Model\BlockFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
    private $blockFactory;

    public function __construct(BlockFactory $blockFactory) {
        $this->blockFactory = $blockFactory;

    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $cmsBlockData = [
            'title' => "Your CMS Static Block",
            'identifier' => "your-cms-static-block",
            'content' => "<h1>Write your custom cms static block content here</h1>",
            'is_active' => 1,
            'stores' => [0],
            'sort_order' => 0

After completing the above steps run the below SSH command in your Magento 2 installed root directory,

php bin/magento setup:upgrade

Then, clear all the Magento cache and check whether the CMS block has been successfully created on Magento 2 admin by navigating to Magento 2 Admin > CONTENT > Blocks.

Note: We have tested the above code on Magento 2.3.

Read Also: Magento 2: How to Call CMS Static Block in Phtml File

Hope this helps.

One Comment on “Magento 2: Creating CMS Static Block Using Installable Script”

Leave a Reply

Your email address will not be published. Required fields are marked *