Magento 2 create CMS page programmatically

Follow the below steps to create CMS page programmatically.

Create UpgradeData.php and define upgrade()

File : app/code/PHPCodez/First/Setup/UpgradeData.php

<?php
 namespace Vendor\Module\Setup;
 use Magento\Framework\Setup\UpgradeDataInterface;
 use Magento\Framework\Setup\ModuleContextInterface;
 use Magento\Framework\Setup\ModuleDataSetupInterface;
 
 class UpgradeData implements UpgradeDataInterface {
 
 protected $_pageFactory;
 
 
 public function __construct(\Magento\Cms\Model\PageFactory $pageFactory) {
 $this->_pageFactory = $pageFactory;
 }
 
 public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
 $setup->startSetup();
 
 if (version_compare($context->getVersion(), '0.1.4') < 0) {
 $page = $this->_pageFactory->create();
 $page->setTitle('PHPCodez CMS page')
 ->setIdentifier('phpcodez-cms-page')
 ->setIsActive(true)
 ->setPageLayout('1column')
 ->setStores(array(0))
 ->setContent('This is a test Page created by PHPCodez. Cheers !!!')
 ->save();
 }
 
 $setup->endSetup();
 }
 }

Setup the module version

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
 <module name="PHPCodez_First" setup_version="0.1.4"/>
</config>

Purge cache and deploy static content.

php bin/magento cache:flush
php bin/magento setup:static-content:deploy -f

Leave a Reply

Your email address will not be published. Required fields are marked *