Showing results for 
Search instead for 
Did you mean: 

Get websites

Get websites

I'm attempting to get all websites to use in a custom template. I've created the following in my block;


public function getWebsites()
   return $this->_storeManager->getWebsites();

I'm then attempting to iterate over the websites in my template using this;


<?php foreach ($block->getWebsites() as $website): ?>

When the page attempts to load, i get;


Warning: Invalid argument supplied for foreach() 


I've tried every possible variant of this but can't seem to get it working. It's quoted multiple times across numerous forums as being the correct way to retrieve all websites, but it just doesn't work for me.


Re: Get websites

Hello Scorpio,


First of all, check if everything is correct in the class block:


namespace YOUR\MODULE\Block;

use Magento\Framework\View\Element\Template;
use Magento\Store\Model\StoreManagerInterface;

class YourBlock extends Template
    protected $_storeManager;

    public function __construct(
        Context $context,
        StoreManagerInterface $storeManager,
        array $data = []
    ) {
        $this->_storeManager = $storeManager;
        parent::__construct($context, $data);

    public function getWebsites()
        /* Use getWebsites(true) if you need to get websites with default */
       return $this->_storeManager->getWebsites();

Please, also make sure that this class is used in the  template. For this you can add the following code to the template:

<?php echo get_class($block) ?>

The name should be  "YOUR\MODULE\Block\YourBlock".  If name is another, you can change it in layout.


Hope it will help.



Plumrocket Team


Re: Get websites

Thanks for the response. I've tried adding the use directives and functions to the block class and then calling getWebsites() from my template, but it's not working.


Adding your line; <?php echo get_class($block) ?> gives me "Magento\Store\Block\Switcher\Interceptor" on the resulting page.

Adding the line; <?php print_r($block->getWebsites()); ?> doesn't give me anything.


It just looks like getWebsites() isn't returning anything, but also not raising any error when it fails.


EDIT: After some more research I came across a blog article in which a comment stated that blocks cannot be overridden in themes? Is this the case? If so, then clearly my function isn't being called.


I'm trying to override the language switching. I'm clearly overriding the PHTML file because it's generating an error when I try to call getWebsites(). For the block there are two PHP files;




Can someone confirm what file(s) I need to copy and to where in order to override? Do I need to create any other files?