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();    
       }
      

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

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. Required fields are marked *