How To

How to Add Dynamic CMS Block Programmatically in Magento 2

Hello Magento Friends,

Today letā€™s learn How to Add Dynamic CMS Block Programmatically in Magento 2.

Blocks can be placed anywhere on the page. Blocks that contain content are known as CMS Blocks. CMS Blocks are used to display text, video, or images. It can also be used to display dynamic information on the page. You can Add Dynamic CMS Block Programmatically in Magento 2. Letā€™s learn how

Steps to Add Dynamic CMS Block Programmatically in Magento 2:

Step 1: Navigate to the below path

app\code\Vendor\Extension\Setup\InstallData.php

Now add the code as follows

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' => 'Custom Cms Block',
            'identifier' => 'custom_cms_block',
            'content' => 'Your Custom Text Here',
            'is_active' => 1,
            'stores' => [0],
            'sort_order' => 0
        ];

        $this->blockFactory->create()->setData($cmsBlockData)->save();
    }
}

Step 2: Now, Call CMS Block. For that go to the below path

app\code\Vendor\Extension\view\frontend\templates\callcmsblock.phtml

echo $block -> getLayout( )
Ā Ā Ā Ā Ā Ā Ā Ā Ā  Ā  Ā  Ā  Ā  -> createBlock('Magento\Cms\Block\Block')
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā  -> setBlockId('custom_cms_block') // CMS block Identifier
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā ->toHtml();

When you first install your module into Magento, at that time you need to Call CMS Block as given above.

Step 3: Now run the below commands

sudo php bin/magento setup:upgrade
sudo php bin/magento setup:static-content:deploy -f
sudo php bin/magento cache:flush

Result:

Your CMS block is created in the Admin Panel at the below path

Content > Elements > Blocks

Conclusion:

Hence, accordingly, you can Add Dynamic CMS Block Programmatically in Magento 2. Also look into How to Create New CMS Block in Magento 2. If you face any difficulty with the implementation of the above steps, drop a comment. I will be back to you as quickly as possible. Do share the article with your friends and keep yourself updated!

Happy Coding!

Click to rate this post!
[Total: 5 Average: 4.8]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate šŸŽ–ļø Certified Magento DeveloperšŸ‘Øā€šŸ’». He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fondā¤ļø of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.šŸ

View Comments

  • hello
    I want to make a block that holds a card with some text and an image of a category.
    what should I do?
    should I change the content in the array below or what
    $cmsBlockData = [
    'title' => 'Custom Cms Block',
    'identifier' => 'custom_cms_block',
    'content' => 'Your Custom Text Here',
    'is_active' => 1,
    'stores' => [0],
    'sort_order' => 0
    ];

Recent Posts

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

20 hours ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

20 hours ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

2 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

3 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

5 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

5 days ago