This article covers:
- How to add website switcher in a multi-website environment
- How to extend the default Magento Store module
The server environment:
- Apache 2.4, Ubuntu 18.04
- Magento 2.3.0
- Multi-website configuration, in this case each website has one store view
Point it out if incorrect: it appears to us that up until 2.3 there is no default website switcher solution in Magento. Due to the limitation of time, we can only demonstrate a quick and dirty way to add your own website switcher.
Please keep it in mind that a website switcher is different from the store switcher, which is usually covered in most third party Magneto themes.
Step 1 – Create Magento Websites and Stores
You can create stores by going to Magento 2 Admin: Stores -> Settings -> All Stores and create your own websites and store views.
One thing
Step 2 – Extend Default Magento Store Template Language.phtml
We found it’s the easiest way to add your own website switcher scripts by extending the default language switcher. Of course, it’s always better to write your own module for such tasks.
In our custom theme, above template file is already included so all we did is modify it in our child theme. Otherwise you can copy:
vendor/magento/module-store/view/frontend/templates/switch/languages.phtml
To your custom theme:
{vendor}/{child_theme}/Magento_Store/templates/switch/languages.phtml
Before the start of the Language switcher, add below code:
[php] <!– Website switcher –> <?php $storeManager = \Magento\Framework\App\ObjectManager::getInstance()->get(‘\Magento\Store\Model\StoreManagerInterface’); $websites = $storeManager->getWebsites(); $websiteid = $storeManager->getWebsite()->getWebsiteId(); ?> <div class="switcher store switcher-store" id="switcher-store"> <strong class="label switcher-label"><span><?php echo __(‘Select Store’) ?></span></strong> <div class="actions dropdown options switcher-options"> <?php foreach ($websites as $website): ?> <?php if ($websiteid == $website->getId()): ?> <div class="action toggle switcher-trigger" role="button" tabindex="0" data-mage-init='{"dropdown":{}}’ data-toggle="dropdown" data-trigger-keypress-button="true" id="switcher-store-trigger"> <strong> <span><?php echo $block->escapeHtml($website->getName()) ?></span> </strong> </div> <?php endif; ?> <?php endforeach; ?> <ul class="dropdown switcher-dropdown" data-target="dropdown"> <?php foreach ($websites as $website): ?> <?php if (!($websiteid == $website->getId())): ?> <li class="switcher-option"> <a href='<?php echo $website->getDefaultStore()->getBaseUrl() ?>’> <?php echo $block->escapeHtml($website->getName()) ?> </a> </li> <?php endif; ?> <?php endforeach; ?> </ul> </div> </div> <!– Eof website switcher –> [/php]Yes, we used objectManager which is not recommended. We’re planning to write a custom module in the near future.