Magento 2 CMS blocks allow you to put specific content in the spotlight. If you share some announcements, discounts, or special offers using CMS blocks. This makes your customers finding and applying them much more probable.
You can create a CMS block in the admin panel, that's one way. However, it's also possible to create new CMS blocks in Magento 2 programmatically. This is exactly what you'll learn today.
First, you need to create a basic Magento 2 module and add the Setup folder to it. Then, create an InstallData.php file in app/code/Vendor/Extension/Setup and add the following code:
<?php
namespace Vendor\Extension\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' => 'New Cms Block',
'identifier' => 'new_cms_block',
'content' => 'Your CMS Block Content',
'is_active' => 1,
'stores' => [0],
'sort_order' => 0
];
$this->blockFactory->create()->setData($cmsBlockData)->save();
}
}
Then, you can call the created CMS block on the preferred phtml file using the following method:
echo $block -> getLayout( )
-> createBlock('Magento\Cms\Block\Block')
-> setBlockId('custom_cms_block') // CMS block Identifier
->toHtml();
To finish it up, run the deployment commands:
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush
Note: if you don't want your website to be down during deployment, try these zero downtime deployment commands for Magento 2.
Finally, you can check if your Magento 2 CMS block is created in the Content > Blocks grid:
That's all the steps you need to create new CMS blocks in Magento 2 programmatically. But this is just the first step. You also need to manage the blocks smartly to make them effective.
For instance, you can schedule CMS blocks or restrict their display. This way, you get to prepare your campaigns in advance and boost your efforts.