Magento2 Get Current Website Code Programmatically

If you want to get the current website code programmatically using Magento 2, you can get it by StoreManagerInterface from where we can collect all the information of your Magento 2 store.

By default, single website have default assigned code is “default”.

If we are working with multiple website eCommerce stores, you need to fetch current website code for respected website programmatically on certain situation.

<?php declare(strict_types=1);
 
namespace Magemeta\Currentstore\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;
    }
}

Above code will return the current website code.

Hope this helps you guys!

Leave a Reply