How to get current AREA CODE in Magento 2 - Kishan Savaliya

Welcome to Kishan Savaliya's Magento 2 Blog.In this blog post, I will show you how to get current area code. 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 SK\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.


Hope you may like this article and can understand this easily. You can add comments below in case if you have any questions regarding this article or if I missed anything here. I will check and get back to you with proper solution.

If you enjoyed this blog post, share it with friends!