How To Check If The Current Area Is Frontend Or Backend In Magento 2
The Magento 2 store admin gets additional privileges for efficiently fulfilling their responsibility as a store admin.
For example, the admin gets the facility to use a particular shipping or payment method while placing an order from the backend.
However, to implement admin-exclusive features, you need to first check if the current area is frontend or backend in Magento 2. The method given below allows checking if it is frontend or backend.
Check the area of the current URL in Magento 2 with any of the two methods:
And, you get one of these outputs as frontend, adminhtml, or webapi_rest.
Method to check if the current area is frontend or backend in Magento 2:
-
With objectManager
123$objectManager = \Magento\Framework\App\ObjectManager::getInstance();$state = $objectManager->get('Magento\Framework\App\State');echo $state->getAreaCode(); -
With class method
12345678910111213141516171819<?phpnamespace Vendor\Extension\Block;use Magento\Framework\App\State;use Magento\Framework\View\Element\Template;use Magento\Framework\View\Element\Template\Context;class Index extends Template{protected $state;public function __construct(Context $context, State $state array $data = []){parent::__construct($context, $data);$this->state = $state;}public function getArea(){return $this->state->getAreaCode();}}?>
That’s it.
Any doubts?
Mention them in the Comments section below. I’ll help you with the issue.
Do share the solution with fellow developers via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How To Import Product Images From URL In Magento 2
Action-packed Steps to Configure Customer Group In Magento 2
Next