We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
How to create CMS Page Programmatically in Magento 2
Making a CMS page programmatically in Magento 2 is also an important method you want to learn. As soon as generating a CMS page successfully, you will have complete control of the management of the content on the CMS page. There, you can edit or modify or delete any data as necessary. With a CMS page, it is adjustable to intervene in the addition of the content.
In this blog, you will learn how to create a CMS page programmatically in Magento 2.
Steps to creating CMS Page programmatically
These are the four steps you need to follow to create a CMS page programmatically
- Create UpgradeData.php file
- Insert UpgradeData class
- Setup the module version
- Run the upgrade command
Step#1: Create UpgradeData.php file
Create this Setup/UpgradeData.php file in your module.
Step#2: Insert UpgradeData class
Utilize UpgradeData class as the under, then add the needed model with dependency injection and a code script to generate a new CMS page.
<?php
namespace Vendor\Module\Setup;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
/**
* @codeCoverageIgnore
*/
class UpgradeData implements UpgradeDataInterface
{
/**
* @var \Magento\Cms\Model\PageFactory
*/
protected $_pageFactory;
/**
* Construct
*
* @param \Magento\Cms\Model\PageFactory $pageFactory
*/
public function __construct(
\Magento\Cms\Model\PageFactory $pageFactory
) {
$this->_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('CMS page programmatically')
->setIdentifier('cms-page-programmatically')
->setIsActive(true)
->setPageLayout('1column')
->setStores(array(0))
->setContent('We create a CMS Page programmatically in Magento 2.')
->save();
}
$setup->endSetup();
}
}
Step#3: Setup the module version
Open etc/module.xml file, you need to configure your module version in setup_version attribute that should be 1.1
Step#4: Run the upgrade command
Lastly, run the following database upgrade command, then you will achieve the creating new CMS page on your Magento 2 storefront.
bin/magento setup:upgrade
These are all steps that allow you to create the CMS Page programmatically.
If you are looking for Magento 2 eCommerce website, visit Magento 2 Services.