I’m starting series of short blog posts to share solutions for common Magento 2 problems. In first one I’m going to show how to add CMS Page programmatically in setup scripts.
Use following steps to create CMS page:
1. Create Setup/UpgradeData.php file inside your module.
2. Create UpgradeData class, add required model using dependency injection and then add code which adds new CMS page. Full class below:
_pageFactory = $pageFactory;
    }
    /**
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        if (version_compare($context->getVersion(), '1.1') < 0) {
            $page = $this->_pageFactory->create();
            $page->setTitle('Example CMS page')
                ->setIdentifier('example-cms-page')
                ->setIsActive(true)
                ->setPageLayout('1column')
                ->setStores(array(0))
                ->setContent('Lorem ipsum dolor sit amet, consectetur adipiscing elit.')
                ->save();
        }
        $setup->endSetup();
    }
}3. Change your module version in setup_version attribute in etc/module.xml file, in this case it should be 1.1.
4. Run database upgrade script:
bin/magento setup:upgradeThat’s it, your CMS page should be now visible in Magento 2 backend.

Leave a Reply