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

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

4 hours ago

Best Beginners Guide to Shopify Balance Account

If you are a Shopify admin, using a Shopify Balance Account for your business revenue…

4 hours ago

8 Best Social Login Apps for Shopify Store in 2024

Running an eCommerce business can be incredibly demanding, leaving entrepreneurs little time to focus on…

5 hours ago

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

1 day ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

2 days ago

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

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

2 days ago