7

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()
15

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();
}
  • 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 Aug 1 '16 at 18:00
  • 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. – Giel Berkers Aug 6 '18 at 12:05
  • @Solide How Can I get page information per store view I've tried $this->_pageFactory->create()->setStoreId(1)->load($cmsId) ? – Juliano Vargas Mar 1 '19 at 16:36
10

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
2

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, privacy policy and cookie policy

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