'Magento 2 : how to getbaseurl for different website?

I have set the different Base Url for different website views, so How to get the baseUrl for a different websites with getBaseUrl() function.

~~ Thank you in advance!



Solution 1:[1]

You can get BaseUrl by store object. So you will have to first load the store from website. Check below generic code which will give all website's base URLs.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager =  $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$websites = $storeManager->getWebsites();
 foreach ($websites as $website) {
     foreach ($website->getStores() as $store) {
         $wedsiteId = $website->getId();
         $storeObj = $storeManager->getStore($store);
         $storeId = $storeObj->getId();
         echo $url = $storeObj->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);
     }
 }

If you are using constructor you can directly use \Magento\Store\Model\StoreManagerInterface $storeManager instead of objectmanager.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1