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.

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

2 Answers 2


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;

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


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

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

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" 
         <referenceContainer name="footer">
    <block class="Magento\Cms\Block\Block" name="Promo">
                <argument name="block_id" xsi:type="string">{BlockIdenfier}</argument>

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.