When programming in Magento 2, we at Codingbasics.net often come across the issue of getting the base url of the current store. This was very easy to do in Magento 1, but in the second version of the shopping cart CMS it’s done a bit differently. In this post, we will show you how to do this.
To get the base URL in Magento 2 use the following code.
$this->_storeManager->getStore()->getBaseUrl()
You can also use the following code which gives you the store id as well.
$this->_objectManager->get('Magento\Store\Model\StoreManagerInterface') ->getStore($storeId) ->getBaseUrl();
To get the Media base URL use the following.
$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
And last but not least, to get the link URL use this.
$this->_storeManager->getStore() ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);
Although it’s not recommended, you can also get the base URL directly in phtml by using the direct call of object manager. This can be done with the following code snippet.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $storeManager->getStore()->getBaseUrl();
This is, however, a very resource intensive task that isn’t very efficient. Use this only if no other method works, or if the piece of code is rarely used in your Magento 2 store. If you have more questions or problems, leave a comment in the comment section below and we’ll answer and help you.
The post How to get the Magento 2 Base URL appeared first on Coding Basics.