When developing module or theme in Magento 2, you might need to identify where you are to perform such actions. I will show you how to get current URL in Magento 2.
To get current URL in Magento 2, you will need to inject an instance of \Magento\Framework\UrlInterface
in constructor, so it will be like:
public function __constructor(\Magento\Framework\UrlInterface $url)
{
$this->url = $url;
}
public function getCurrentUrl()
{
return $this->url->getCurrentUrl();
}
If you’re inside the template phtml
, you can directly make call to this method \Magento\Framework\View\Element\AbstractBlock::getUrl()
, it will return the current URL as well.
Beside UrlInterface
, you can also inject an instance of \Magento\Store\Model\StoreManagerInterface $storeManager
to get current URL as well, which works the same way.
$this->storeManager->getStore()->getCurrentUrl();
Have fun ~