Creating CMS page programmatically in Magento 2 is also a crucial method you need to learn. As soon as creating CMS page successfully, you will have full control of the management of the content on the page. There, you can edit or update or delete any data as need. With CMS page, it is flexible to intervene into the change of the content. In previous post, we talk about Create a CMS page in Admin, you also can follow the post to create a sample CMS page in backend.
In this topic, you can know how to insert CMS page programmatically into Magento 2 setup script through specific steps:
UpgradeData
classGenerate Setup/UpgradeData.php
file in your module.
UpgradeData
classUse UpgradeData
class as the below, then add required model with dependency injection and a code script to create 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('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();
}
}
Open etc/module.xml
file, you need to set your module version in setup_version
attribute that should be 1.1
Finally, run the following database upgrade script, then you will complete the creating new CMS page on your Magneto 2 storefront.
bin/magento setup:upgrade
That’s all steps that allow you to create a new CMS page programmatically in Magento 2. Thank you so much for the watching!
Please leave comments if you have any questions, feedbacks.