Magento2 – How to get Current Url

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 Comments

  • Like!! Great article post.Really thank you! Really Cool.

  • please explain it line by line as we are new in Magento 2.

    • Hi Ali,
      Welcome to Magento. Please view my other posts to get familiar with basics.

Leave a Reply

Your email address will not be published.