Magento2 – How to get Current Url

To get url of the current page, the code below works everywhere:
     $objectManagerInstance = \Magento\Framework\App\ObjectManager::getInstance();
     $url = objectManagerInstance -> get('Magento\Framework\UrlInterface');
     echo $url -> getCurrentUrl();
From a .phtml template you can also do it shorter by calling the \Magento\Framework\View\Element\AbstractBlock::getUrl();

Without using objectManager you can use inside your class here

      Initialize your object : private $_urlInterface
      Now declare it inside your class constructor:
      public function __construct(
            Magento\Framework\UrlInterface $urlInterface
      ) {
       $this->_urlInterface = $urlInterface;

      Now in order to get current url, create method to retrieve it:

       public function getCurrentUrl() {
           return $this->_urlInterface -> getCurrentUrl();    

4 Replies to “Magento2 – How to get Current Url”

Leave a Reply

Your email address will not be published. Required fields are marked *