SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH
get current AREA CODE in Magento 2
Magepow.com

How to get current AREA CODE in Magento 2

Hi everyone, Today I will guide you how to get current AREA CODE in Magento 2.

You can get area code using below 2 methods..

  1. Directly using Object Manager.
  2. Using Helper/Block class.

1. Directly using Object Manager

Sometimes, you need to create root scripts to perform some operations, and you want to perform that actions for specific area like frontend or backend. So you can put condition of area code..

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('Magento\Framework\App\State');
echo $state->getAreaCode();

2. Using Helper/Block class

You can get Area code by injecting Magento\Framework\App\State class in your Block or Helper class, this is best practices avoid to use object manager and inject in constructor and use them.

<?php

namespace Magepow\Module\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\App\State;

class Index extends Template
{
    protected $state;

    public function __construct(
        Context $context,
        State $state
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->state = $state;
    }

    public function getAreaCode()
    {
        return $this->state->getAreaCode();
    }
}

Now, you can use this getAreaCode() function to get area code, you can inject above class in your any Block file.

Done, I hope this article will helpful for you.