How to Get Current URL in Magento 2

When editing your store, you will need URLs to make any changes quickly. 

In this blog, learn how to automatically get the current URL in Magento 2; then, you do not have to find and type URLs when developing a page or attaching the URLs anywhere. 

There are two ways to get your current URL in your Magento 2 store:

  • Without using an object manager
  • UrlInterface dependence

Here, I will show you both methods, so let’s start.

Steps to Get Current URL in Magento 2 – Without Using an Object Manager

This is one of the easiest ways to get the current URL in a Magento 2 PHTML file. 

Add the following code: 

$currentUrl = $block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);

This same code also works for block PHP classes, you only need to replace $block with $this.

$currentUrl = $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);

Steps to Get Current URL in Magento 2  Using UrlInterface Dependence

This is a recommended method since you can’t directly use the object manager. 

Example: 

$urlInterface = \Magento\Framework\App\ObjectManager::getInstance() ->get(\Magento\Framework\UrlInterface::class); $currentUrl = $urlInterface->getCurrentUrl();

At times, you will come across this code as well:

$storeManager = \Magento\Framework\App\ObjectManager::getInstance() ->get(\Magento\Store\Model\StoreManagerInterface::class); $currentUrl = $storeManager->getStore()->getCurrentUrl();

The solution would work for you but will give you a URL with extra parameters. 

That’s all you need to do to get the current URL in Magento 2. Go ahead and try this solution now!  

Table of Contents