How to Get Current URL in Magento 2
Magento 2 is a flexible and feature-rich eCommerce platform with many different functionalities that allows customizing your online store as per the business requirements!
Customizing the admin panel and frontend is easily possible using different tactics. While running an online store, there may be a system requirement to automatically get the current URL in Magento 2.
Facilitates admin by making their work easier as they do not have to find and type URLs when developing a page or attaching the URLs anywhere. In such a scenario, use the below solution to get the current URL in Magento 2.
Steps to Get Current URL in Magento 2
Create a block in the Vendor\Module\Block path.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php namespace Vendor\Module\Block; use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\View\Element\Template\Context; class Test extends \Magento\Framework\View\Element\Template { private $storeManager; public function __construct(StoreManagerInterface $storeManager,Context $context,array $data = []) { $this->storeManager = $storeManager; parent::__construct($context, $data); } public function getCurrentUrl() { return $this->storeManager->getStore()->getCurrentUrl(); } } |
Create block in Vendor\Module\view\frontend\templates path.
1 2 3 |
<?php $block->escapeUrl($block->getCurrentUrl()); ?> |
That’s it.
If you have any doubts regarding this post, just mention them in the comments section below.
I would be happy to help.
Feel free to share the solution with the Magento community via social media.
Thank You.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Get Available Currency in Magento 2
New Magento 2 Extensions & Updates [January 2022]
Next