In this post I am going to explain How to Identify Current Page Type in Magento 2.
Sometimes when you are working on custom development in Magento 2 then, you need to know what the current type of page being viewed is.
You can identify whether the current page is a category page, product page, checkout page, the home page, or CMS page. You can also customize or add the functionalities based on the current page.
Using below code snippet you can get current page type.
Add below code snippet in Block class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php namespace <Vendor>\<Module>\Block; class Blockname extends \Magento\Framework\View\Element\Template { protected $context; public function __construct( \Magento\Framework\App\Action\Context $context, array $data = [] ) { $this->context = $context; parent::__construct($context, $data); } public function getCurrentPage() { return $this->context->getFullActionName(); } } |
Add below code snippet in template file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //Home Page if ($block->getCurrentPage() == 'cms_index_index') { // Do something on home page only } //CMS Page if ($block->getCurrentPage() == 'cms_page_view') { // Do something on CMS pages only } //Category View Page if ($block->getCurrentPage() == 'catalog_category_view') { // Do something on category view page only } //Product View Page if ($block->getCurrentPage() == 'catalog_product_view') { // Do something on product view page only } |
That’s it. Enjoy Magento 2!!
Check this Best Magento 2 Tutorial.
Thank You.
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!
Leave a Reply