Question

I am using the following code to check if the current page is Product detail page:

$objectManagerCms = \Magento\Framework\App\ObjectManager::getInstance();
$registry = $objectManagerCms->get('Magento\Framework\Registry');
$currentProduct = $registry->registry('current_product');
if ($currentProduct) {
    // Custom code
}

Now how to check if current page is a CMS page?

Was it helpful?

Solution

There are no registry variable add at cms page.

So, if you want to check a page is CMS page then you need to check current controller and action name means Full action name

Best practices

In Magento2, every block has request Object ,So you can get current page full action name via

$block->getRequest()->getFullActionName();

Code:

$currentFullAction = $block->getRequest()->getFullActionName();
$cmspages = array('cms_index_index','cms_page_view');
if(in_array($currentFullAction, $cmspages)){
    //CMS page
}

OTHER TIPS

Try to use below code in your .phtml file

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$request = $objectManager->get('\Magento\Framework\App\Request\Http');
$checkModule = $request->getModuleName();
if($checkModule == 'cms'){
    echo "cms page";
}else{
    echo "not cms page";
}
?>

The registry class could be used in many places. Thus, it's relatively weak check. I suggest you to check full action name of request, like so:

\Magento\Framework\App\Request\Http::getFullActionName() == 'catalog_product_view'
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top