Retrieve website code by website id programmatically using Magento 2.
Many times, you have website id available but you have to fetch website code based on id, You need to use the StoreManagerInterface interface.
You can fetch current website code by below code snippet,
<?php declare(strict_types=1); namespace Jesadiya\MyWebsite\Model; use Psr\Log\LoggerInterface; use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\Exception\LocalizedException; /** * Class Config */ 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 by id * * @param int $id * * @return string|null */ public function getWebsiteCodeById(int $id): ?string { try { $websiteData = $this->storeManager->getWebsite($id); $websiteCode = (string)$websiteData->getCode(); } catch (LocalizedException $localizedException) { $websiteCode = null; $this->logger->error($localizedException->getMessage()); } return $websiteCode; } }
Call function,
echo $this->getWebsiteCodeById(1);
Output:
Returns Website code based on Id. (for 1, its value is base)