3

I would like to add the magento website name to the top header beside the language switcher.

Magento_Store/templates/switch/languages.phtml

I can get the id by using,

echo $block->getCurrentWebsiteId();

How do I get the website name?

5 Answers 5

3

In the current Magento 2.3.X versions (perhaps older as well), the above is definitely not a best practice. Instead, inject the interface \Magento\Store\Api\WebsiteRepositoryInterface as a dependency and call upon the repository as follows:

$website = $this->websiteRepository->getById(42);
$website->getName();
1
public function __construct(

        \Magento\Store\Model\Website $websiteModel
    ..........
)
{
    $this->_websiteModel = $websiteModel;
}


public function getWebsiteName($websiteId)
    {
        $collection = $this->_websiteModel->load($websiteId,'website_id');
        return $collection->getName();
    }
0

in your block file, you can use below code :

public function __construct(
    \Magento\Store\Model\ResourceModel\Website\CollectionFactory $websiteCollectionFactory,
    ..........
)
{
    $this->_websiteCollectionFactory = $websiteCollectionFactory;
}

public function getWebsiteName()
{
    //$websiteId is your current website id
    $collection = $this->_websiteCollectionFactory->create()->load($websiteId,'website_id');
    $websiteData = $collection->getData();
    $websiteName = $websiteData[0]['name'];
    return $websiteName;
}

You can now call getWebsiteName in your phtml file to display the website name.

2
0

From your phtml you could get the current website name doing something like this:

$stores = $block->getStores();
foreach($stores as $store){
    if($store->getCode() == $block->getCurrentStoreCode()){
        $websiteName = $store->getWebsite()->getName();
    }
}

So you don't have to change the block.

0
public function getWebsiteName($websiteId)
{  
   $collection = $this->_websiteCollectionFactory->create();
   $websiteData = $collection->addFieldToFilter('website_id',$websiteId);

   foreach($websiteData->getData() as $websiteName):
      $webName = $websiteName['name'];
   endforeach;

   return $webName;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.