Create CMS pages programmatically in Magento2
Creating a CMS pages in Magento is simple as navigate to Admin Panel -> CMS -> Pages. But while you developing your extension you might need to create a Magento CMS Page programmatically. Here is the way how you can achieve it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
namespace Ayngaz\CmsInstall\Setup; use Magento\Cms\Api\BlockRepositoryInterface; use Magento\Cms\Api\Data\BlockInterface; use Magento\Cms\Api\Data\BlockInterfaceFactory; use Magento\Cms\Api\Data\PageInterface; use Magento\Cms\Api\Data\PageInterfaceFactory; use Magento\Cms\Api\PageRepositoryInterface; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; class InstallData implements InstallDataInterface { /** * @var PageRepositoryInterface */ private $pageRepository; /** * @var PageInterfaceFactory */ private $pageInterfaceFactory; public function __construct( PageRepositoryInterface $pageRepository, PageInterfaceFactory $pageInterfaceFactory ) { $this->pageRepository = $pageRepository; $this->pageInterfaceFactory = $pageInterfaceFactory; } /** * Installs data for a module * * @param ModuleDataSetupInterface $setup * @param ModuleContextInterface $context * @return void */ public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $this->createCmsPage(); } /** * Create a CMS page */ private function createCmsPage() { /** @var PageInterface $cmsPage */ $cmsPage = $this->pageInterfaceFactory->create(); $cmsPage->setIdentifier('page-identifier') ->setTitle('Page Title') ->setContentHeading('Content Heading') ->setContent('Page HTML content') ->setPageLayout('1column') ->setData('stores', [0]); $this->pageRepository->save($cmsPage); } } |
That’s it!. Clear cache and upgrade magento.
1 2 3 4 5 |
rm -rf var/* rm -rf pub/static/* php bin/magento setup:upgrade //(only for new extension) php bin/magento setup:static-content:deploy chmod -R 777 var pub/static |