Get Current Website Code in Magento 2

Posted by

In Magento 2, you may need to retrieve the current website code programmatically for various purposes, such as customization, module development, or data processing. This article will guide you through the process of obtaining the current website code using Magento 2 code snippets.

Steps to Get Current Website Code in Magento 2

  1. Initialize the Context Object: To access the website code, you first need to initialize the context object in your code. This object provides information about the current store and website.
  2. Retrieve the Website Code: Using the initialized context object, you can retrieve the current website code. The website code uniquely identifies each website in Magento 2.

Code Example

Below is an example code snippet that demonstrates how to obtain the current website code programmatically in Magento 2:

<?php
namespace Company\Example\Helper;

class WebsiteCodeExample
{
   /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */    protected $storeManager;

    /**
     * Constructor
     *
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     */    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        $this->storeManager = $storeManager;
    }

    public function getCurrentWebsiteCode()
    {
         return $this->storeManager->getWebsite()->getCode();
    }
}

Conclusion

Obtaining the current website code in Magento 2 is essential for various development tasks. By following the steps outlined in this article and utilizing the provided example code, you can easily retrieve the current website code programmatically in Magento 2.

Leave a Reply

Your email address will not be published. Required fields are marked *