Magento 2 Get List of All Websites On Frontend

 

To get the list of all websites on frontend, we can use the storeManager variable, which is an in-built protected variable of every block extending MagentoFrameworkViewElementTemplate.
1) Calling in Block class file:

In our block class, we can directly get all websites by following code line:

$this->_storeManager->getWebsites();

If we want to call this in block template, simply create a method(function) and write like below:

public function getWebsites() {
$this->_storeManager->getWebsites();
}

Then call this method in your template as given below:

$block->getWebsites();

2) Calling in non-block class file:

If we want to get all websites in a controller or any other non-block class, we need to use dependency injection (DI) in the constructor to be able to use the storeManager code like above in block method we declared:

protected $_storeManager;

public function __construct(MagentoStoreModelStoreManagerInterface $storeManager)
{
$this->_storeManager = $storeManager;
}

Leave a Reply