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

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

7 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

1 day ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

1 day ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

2 weeks ago