In this post, we will show you how to get base url and current url in Magento 2.
Contents
If you want to get Base url:
1 |
$storeManager->getStore()->getBaseUrl(); |
Where $storeManager is instance of \Magento\Store\Model\StoreManagerInterface
You also can use ObjectManager if $storeManager is not available
1 2 3 |
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $storeManager->getStore()->getBaseUrl(); |
For Getting Media Url Use Below code:
1 2 3 |
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); |
Get Static content Url
1 2 3 |
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC); |
Get Current URL
1 2 3 |
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $storeManager->getStore()->getCurrentUrl(); |
However, using object manager is not a recommend way. You should init $storeMaanger variable in __construct() method
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/* @var \Magento\Store\Model\StoreManagerInterface */ protected $_storeManager; public function __construct( ...... \Magento\Store\Model\StoreManagerInterface $storeManager ....... ) { ..... $this->_storeManager = $storeManager; ..... } |
Then use following code to get URLs
1 2 3 4 5 6 7 8 |
// Base URL $baseUrl = $this->_storeManager->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB); // Static Content URL $statiContentUrl = $this->_storeManager->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC); // Media URL $mediaUrl = $this->_storeManager->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); // Link URL $linkUrl = $this->_storeManager->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK); |
This is the guide to get base URL and other URLs in Magento 2. If that you have any queries about the article or any questions in general, use the comment section below or contact us