Get current CMS page id in Magento2

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();
}

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

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();
?>

Tags:

Magento2