Create CMS Block By Installer In Magento 2 – Here I’m going to explain you how you can create cms block by patch data installer in magento2.
First of all create a “AddCustomCmsBlock.php” file on location Vendor\Module\Setup\Patch\Data then use below code snippet.
<?php
namespace Vendor\Module\Setup\Patch\Data;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Cms\Model\BlockFactory;
class AddCustomCmsBlock implements DataPatchInterface
{
/**
* @param BlockFactory $blockFactory
*/
public function __construct(
BlockFactory $blockFactory
) {
$this->blockFactory = $blockFactory;
}
/**
* @inheritdoc
*/
public function apply()
{
$cmsBlockData = [
'title' => 'Custom CMS Block',
'identifier' => 'custom_cms_block',
'content' => "<h1>Write your custom cms block content.......</h1>",
'is_active' => 1,
'stores' => [0],
'sort_order' => 0
];
$this->blockFactory->create()->setData($cmsBlockData)->save();
}
/**
* @inheritdoc
*/
public static function getDependencies()
{
return [];
}
/**
* @inheritdoc
*/
public function getAliases()
{
return [];
}
}
Note: You can call cms block on any phtml file by using below code
echo $block->getLayout()
->createBlock('Magento\Cms\Block\Block')
->setBlockId('custom_cms_block') // cms block identifier
->toHtml();

In this way, we can create CMS block programmatically by installer file. Thanks…
$setup->startSetup();
if (version_compare($context->getVersion(), ‘1.0.0’) ‘Custom CMS Block’,
‘identifier’ => ‘custom_cms_block’,
‘content’ => “Write your custom cms block content…….”,
‘is_active’ => 1,
‘stores’ => [0],
‘sort_order’ => 0
];
$this->blockFactory->create()->setData($cmsBlockData)->save();
}
$setup->endSetup();