1

How to Add CMS Block in Magento2 programatically.

I want to add a cms block in app/code insstead of app/design using layout or xml files.

1
  • Your original question is about added CMS block programmatically or something different you are looking? Commented Jun 1, 2022 at 10:55

2 Answers 2

0

You can create in setup script or controller.

public $blockFactory;

public $blockRepository;

public function __construct(
    PageFactory $pageFactory,
    \Magento\Cms\Model\BlockFactory $blockFactory,
    \Magento\Cms\Model\BlockRepository $blockRepository
  )
{
    $this->resultPageFactory = $resultPageFactory;
    $this->blockFactory = $blockFactory;
    $this->blockRepository = $blockRepository;
}


yourfunction()
{
    $Page = [
    'title' => 'Your page title',
    'identifier' => 'your-page',
    'stores' => [0],
    'is_active' => 1,    
    'content' => 'test content',
    'page_layout' => '1column'
    ];

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

Ref : How to add a CMS block programmatically in Magento 2?

1
  • I want to add header and footer using cms block through layout.xml and phtml only. Commented May 31, 2022 at 6:57
0

Create a module like app/code/VendorName/ModuleName/

then create layout file default.xml at app/code/VendorName/ModuleName/view/frontend/layout

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
         <referenceContainer name="footer">
    <block class="Magento\Cms\Block\Block" name="Promo">
            <arguments>
                <argument name="block_id" xsi:type="string">{BlockIdenfier}</argument>
            </arguments>
    </block>
        </referenceContainer>
    </body>
</page>

Replace {BlockIdenfier} with your cms block identifier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.