Magento2 – How to Update & Create CMS Static Pages Programmatically

cms-pagesdata-installmagento2programmatically

How can update an existing CMS static Page and how to create a new CMS static Page – programmatically

Best Answer

Here is an example how to insert cms data in m2

Here is an example how to update cms data in m2

Now you can try following way for insert cms data:


public function __construct(
    \Magento\Cms\Model\PageFactory $pageFactory
) {
    $this->pageFactory = $pageFactory;
}

And now:



$cmsPage = [
    'title' => 'TEST TITLE',
    'identifier' => 'test-content-1',
    'page_layout' => '1column',
    'content' => 'test content 1',
    'is_active' => 1,
    'store_id' => [0],
    'sort_order' => 22
];
$this->pageFactory->create()->setData($cmsPage)->save();
$setup->endSetup();

For Update:


$newPageContent = 'NEW PAGE CONTENT';
$newPage = $this->pageFactory->create()->load(
    'test-content-1',
    'identifier'
);
if ($newPage->getId()) {
    $newPage->setContent($newPageContent);
    $newPage->save();
}
Related Topic