8

I'm trying to retrieve the current CMS page id in Magento2. Below is the code I used for Magento1.x which obviously doesnt work anymore. But I can not get my head around how to do this for Magento2.

if (Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms') {
    $_pageId = Mage::getBlockSingleton('cms/page')->getPage()->getPageId();
}

Using the registry as shown below wont work.

 $this->_coreRegistry->registry('cms_page')->getId()

4 Answers 4

17

Ok, I found out after digging around in the CMS helper function.

protected $_page;

public function __construct(
    ...
    \Magento\Cms\Model\Page $page,
    ...
    array $data = []
) {
    parent::__construct($context, $data);
    ...
    $this->_page = $page;
    ...
}

if ($this->_page->getId()) {
    $pageId = $this->_page->getId();
}
3
  • This code is an example on how to include the functionality in a block or helper class. It is not to be copied 1 on 1. Check out the CMS helper for more context at \vendor\magento\module-cms\Helper\Page.php
    – Solide
    Commented Aug 1, 2016 at 18:00
  • 1
    Is this really the right way to achieve this? It does seem kind of weird to use DI to inject an object that holds a state. Commented Aug 6, 2018 at 12:05
  • @Solide How Can I get page information per store view I've tried $this->_pageFactory->create()->setStoreId(1)->load($cmsId) ? Commented Mar 1, 2019 at 16:36
14

With ObjectManager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cmsPage = $objectManager->get('\Magento\Cms\Model\Page');

echo $cmsPage->getIdentifier(); //Get Current CMS Page Identifier
echo $cmsPage->getId(); //Get Current CMS Page ID

With Factory Method

protected $_cmsPage;

public function __construct(
    ...
    \Magento\Cms\Model\Page $cmsPage,
    ...
) {
    ...
    $this->_cmsPage = $cmsPage;
    ...
}

echo $this->_cmsPage->getIdentifier(); //Get Current CMS Page Identifier
echo $this->_cmsPage->getId(); //Get Current CMS Page ID
3

Try this solution. This will help you to identify the current CMS page.

<?php
    $objectManagerCms = \Magento\Framework\App\ObjectManager::getInstance();
    $cmsPage = $objectManagerCms->get('\Magento\Cms\Model\Page');
    echo $cmsPage->getIdentifier();
    echo $cmsPage->getId();
?>
-1

If you in same layout cms_page_view

$pageId= $this->getLayout()->getBlock("cms_page")->getPage()->getId();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.