We can get Current website code programmatically using Magento 2 by StoreManagerInterface.
By default, Single website have default assigned code is “default”
If you are working with multiple website eCommerce stores, You need to fetch current website code for respected website programmatically on some occasion.
You can fetch current website code by below code snippet,
<?php declare(strict_types=1); namespace Rbj\MyWebsite\Model; use Psr\Log\LoggerInterface; use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\Exception\LocalizedException; class Config { /** * @var StoreManagerInterface */ private $storeManager; /** * @var LoggerInterface */ private $logger; /** * Constructor * * @param StoreManagerInterface $storeManager * @param LoggerInterface $logger */ public function __construct( StoreManagerInterface $storeManager, LoggerInterface $logger ) { $this->storeManager = $storeManager; $this->logger = $logger; } /** * Get website code * * @return string|null */ public function getWebsiteCode(): ?string { try { $websiteCode = $this->storeManager->getWebsite()->getCode(); } catch (LocalizedException $localizedException) { $websiteCode = null; $this->logger->error($localizedException->getMessage()); } return $websiteCode; } }
Call function,
echo $this->getWebsiteCode();
Output:
Returns Current Website code.