Magento 2: add CMS Page programmatically

I’m starting series of short blog posts to share solutions for common Magento 2 problems. In first one I’m going to show how to add CMS Page programmatically in setup scripts.

Use following steps to create CMS page:

1. Create Setup/UpgradeData.php file inside your module.

2. Create UpgradeData class, add required model using dependency injection and then add code which adds new CMS page. Full class below:

3. Change your module version in setup_version attribute in etc/module.xml file, in this case it should be 1.1.

4. Run database upgrade script:

That’s it, your CMS page should be now visible in Magento 2 backend.

2 thoughts on “Magento 2: add CMS Page programmatically

  1. Max Pronko says:

    Hi Wojtek,

    Thank you for your article, it is really helpful for developers who want to jump into Magento 2. Few notes I would like to share regarding the article:
    1. It is better to pass \Magento\Cms\Model\PageFactory $pageFactory into __construct() method. The $pageFactory will then create new instance of the \Magento\Cms\Model\Page class.
    2. There is no need to copy $setup variable into $installer. The $installer variable was introduced back in Magento 1. Let’s leave it there.

    Thank you for your post.

  2. Max, thanks for feedback, it makes sense, I updated snippets with proposed changes.

    I was looking for code sample which adds CMS page in core code and I found Magento\Cms\Model\Page instantiated by object manager – it looks this part was not refactored yet.

    Good catch about $installer :-)

Leave a Comment

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