Home » Magento, Magento 217 February 2016

Magento 2: Get Current URL & Base URL

This article shows how we can get current and base URL in Magento 2.

Both Dependency Injection and Object Manager ways of coding are given below.

Using Dependency Injection (DI)

Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of StoreManagerInterface & UrlInterface in the constructor of my module’s block class. Both of them can be used to fetch base and current URL. In below class, in function getStoreManagerData(), object of StoreManagerInterface is used to print the base and current url and in function getUrlInterfaceData() function, object of UrlInterface is used to print the base and current url.

app/code/Chapagain/HelloWorld/Block/HelloWorld.php

See more functions in

MAGENTO_ROOT/vendor/magento/module-store/Model/Store.php
MAGENTO_ROOT/vendor/magento/framework/Url.php

As you can see in the above code, my block class is extending class \Magento\Framework\View\Element\Template. Hence, I can easily get URL and base URL in my template (.phtml) file with the following code:

Using Object Manager

Hope this helps. Thanks.

Magento 2

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed

Comments are closed.