Create CMS block in Magento 2

Create Magento 2 CMS Blocks in Just a Few Minutes!

by admin

The success of the content is dependent upon its presentation. Store owners always try to find ways to display content that is eye-catching, rich and logical. For Magento stores, you can accomplish this by using the Magento CMS Blocks.

 

As you may know, CMS block is a great tool that helps site administrators can easily manipulate and manage the content of the store.  It can be used to display promotional banners, sale blocks, return policies or important information message of the store, etc. Admins can easily add new CMS Blocks with format text, create links and tables, images or videos and set position to show the block on any pages.

 

Let’s follow the step-by-step guide below to create a CMS block quickly!

Create CMS blocks via the Admin panel

Step 1: Go to the Content tab → Blocks

Step 2: Click on Add New Block

Step 3: Fill in Block Title, Identifier, Store view, Content

  • Enter the Block Title to describe your block
  • Enter the Identifier: The characters should be unique and in lowercase. Using the underscore instead of space.
  • Select the Store View to enable the block for.
  • Enter the content for the block. You can place links, images, videos, tables,… in the content.

Step 4: Save Block

Create CMS blocks programmatically

Let’s follow the line of code below to create CMS programmatically!

 <?php
namespace Vendor\Module\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' => '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();
}
}

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();

That’s the end of our tutorial. After this post, we hope that you will be able to create blocks on your own. Besides, we would like to introduce to you Magento 2 Duplicate CMS Page/Block extension that helps to save 80% of the time when duplicating CMS Pages/Blocks with 1 click.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.