How To

How to Get All Stores of All Websites in Magento 2

Hello Magento Friends,

Today we will learn to retrieve all stores of all websites in Magento 2.

Magento 2 provides the option to set up multiple websites and stores. When you need to retrieve the list of all stores, with default Magento you can get the stores for that particular website only. But if you have the requirement to get all the stores regardless of the website, this guide is for you.

Let me explain practically,

As per the above image, Indian-INR and Global-USD stores are available on different websites. So if you want to retrieve a list of all stores no matter what website they are in, you can use the below steps.

Steps to Get All Stores of All Websites in Magento 2:

Step 1: Go to the below file path

app\code\Vendor\Extension\etc\di.xml

Then add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Store\Block\Switcher" type="Vendor\Extension\Block\Switcher"/>
</config>

Step 2: Now move to the following file path

app\code\Vendor\Extension\Block\Switcher.php

After that add the following code snippet

<?php
namespace Vendor\Extension\Block;

use Magento\Directory\Helper\Data;
use Magento\Store\Model\Group;
use Magento\Store\Model\Store;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Url\Helper\Data as UrlHelper;

/**
 * Switcher block
 *
 * @api
 * @since 100.0.2
 */class Switcher extends \Magento\Store\Block\Switcher
{
    /**
     * @var bool
     */
    protected $_storeInUrl;
    /**
     * @var \Magento\Framework\Data\Helper\PostHelper
     */
    protected $_postDataHelper;
    /**
     * @var UrlHelper
     */
    private $urlHelper;
    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Framework\Data\Helper\PostHelper $postDataHelper
     * @param array $data
     * @param UrlHelper $urlHelper
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Data\Helper\PostHelper $postDataHelper,
        array $data = [],
        \Magento\Framework\Url\Helper\Data $urlHelper = null
    )
    {
        $this->_postDataHelper = $postDataHelper;
        parent::__construct($context, $postDataHelper, $data);
        $this->urlHelper = $urlHelper ?: ObjectManager::getInstance()->get(\Magento\Framework\Url\Helper\Data::class);
    }
      /**
     * @return array
     */
    public function getRawAllStores()
    {
        $websites = $this->_storeManager->getWebsites();
        $stores = [];
        foreach ($websites as $website)
        {
            $websiteStores = $website->getStores();
            foreach ($websiteStores as $store)
            {
                /* @var $store \Magento\Store\Model\Store */                if (!$store->isActive())
                {
                    // continue;
                }
                $localeCode = $this->_scopeConfig->getValue(
                    Data::XML_PATH_DEFAULT_LOCALE,
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                    $store
                );
                $store->setLocaleCode($localeCode);
                $params = ['_query' => []];
                if (!$this->isStoreInUrl())
                {
                    $params['_query']['___store'] = $store->getCode();
                }
                $baseUrl = $store->getUrl('', $params);
                $store->setHomeUrl($baseUrl);
                $stores[$store->getGroupId()][$store->getId()] = $store;
            }
        }
        return $stores;
    }
}

Step 3: Finally, run the below commands

php bin/magento setup:di:compile
php bin/magento cache:flush

Conclusion:

Hence, with the help of this method, you can get all stores lists of all the websites of your Magento 2 store. If you face any difficulty, share with me through the comment and stay tuned with us for more Magento solutions.

Happy Coding!

Click to rate this post!
[Total: 2 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

15 hours ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

3 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

3 days ago

Magento 2: How to Add Header and Footer in Checkout

Hello Magento Friends, In today’s blog, we will discuss adding a header and footer to…

4 days ago

Understanding Flexbox Layout in React Native

Hello React Native Friends, Building a visually appealing and responsive mobile app is crucial in…

6 days ago

HYVÄ Themes Releases: 1.3.6 & 1.3.7 – What’s New

We have brought exciting news for Magento store owners. Hyvä Themes recently released 1.3.6 and…

6 days ago