5

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?

3 Answers 3

19

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
}
1
  • Cool, It's working! $block->getRequest()->getFullActionName(); Mar 20, 2020 at 12:37
7

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";
}
?>
2

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'

Your Answer

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

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