How to Identify Current Page in Magento 2 Phtml File
Magento 2 is the most preferred CMS among E-commerce store owners owing to its flexibility and customization ability. It allows fulfilling the business requirements to meet customer expectations or to improve the onsite user experience.
As a part of such a business requirement and customizing the default features, the following solution to identify current page in Magento 2 phtml file can be helpful.
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.
For instance, if you want to add a custom notification bar on a particular page i.e., the Home page or CMS page, that notifies the current deals or festive discounts. Moreover, while working with any custom module, you may need to display the same header on every page instead of the CMS page.
In such cases, you first have to identify the current page and apply conditions like if the current page is a home page then add a notification bar otherwise don’t display it. Or if the current page is a category page then display a percentage discount on the particular product.
Method to Identify Current Page in Magento 2 Phtml File
-
Create Test.php file at app/code/Vendor/Module/Block/
1234567891011121314151617181920212223242526<?phpnamespace Vendor\Module\Block;use Magento\Framework\App\Action\Context;class Test extends \Magento\Framework\View\Element\Template{protected $context;public function __construct(Context $context,array $data = []){$this->context = $context;parent::__construct($context, $data);}public function getCurrentPage(){return $this->context->getFullActionName();}}?> -
Use the below script to get current page in the template file.
123456789101112if ($block->getCurrentPage() == 'catalog_product_view') {//Product page}if ($block->getCurrentPage() == 'catalog_category_view') {//category page}if ($block->getCurrentPage() == 'cms_index_index') {//home page}if ($block->getCurrentPage() == 'cms_page_view') {//cms page}
Simple. Isn’t it?
That’s it.
Any doubts can be mentioned in the Comments section below and I’d be happy to help!
Do share the solution with fellow developers via social media.
Thanks.
2 Comments
You dont need to use this. You can use $block->getRequest()->getFullActionName(); and then check based on what it returns as to what type of page you are on 🙂
Hello Kristy,
Yes, one can do this using such method as well.
Thank You