Create CMS pages programmatically in Magento2

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:

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.

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