How to get media url, static url, link url and base url in Magento 2?

Today we'll show how to get get Media URL, Static URL, Link URL and Base URL in Magento 2. To get URLs in Magento 2, the first you have to define Block file with __construct() method with define storeManagerInterface in construct method.

Create instance of \Magento\Framework\App\ObjectManager to get current store:

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //instance of\Magento\Framework\App\ObjectManager
$storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface'); 
$currentStore = $storeManager->getStore();

Getting Base URL:

$this->_storeManager->getStore()->getBaseUrl()

Getting Media URL:

$mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

Getting Link URL:

$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);

Getting Static URL:

$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC);

That’s the way for getting URLs in Magento 2. Hope that this post is useful for you. In case there is any question, contact us for the help.

Thanks for reading!