Magento 2 – How to Create and Display Custom CMS Static Block on Homepage

magento2magento2.2magento2.2.6

I am able to create CMS Static Block from admin and display it on the homepage, but is there a way to do it programmatically so I can create custom widgets(basically custom HTML/CSS) and display it on the homepage? What's the best way to go about displaying Custom HTML/CSS on the homepage programmatically? Or is modifying the Content in Content>Pages>Home Page is the only way?

Best Answer

Create InstallData.php file at /app/code/VendorName/ModuleName/Setup/InstallData.php

<?php

namespace VendorName\ModuleName\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>Your content added here</h1>",
            'is_active' => 1,
            'stores' => [0],
            'sort_order' => 0
        ];

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

Then, remove your module value from setup_module table and related table also. Now, execute this below command.

php bin/magento s:up
php bin/magento s:s:d -f or php bin/magento s:s:d
php bin/magento c:c

Then, go to admin -> Content -> Blocks and find your static block will be created. Now, add your changes if you need.

Hope, it will helpful for you.

Related Topic